2016-07-26 40 views
-1

我將兩個數組從我的mongodb傳遞到我的express服務器,然後傳入我的模板中。在這個模板中,數組進入我的client.js javascript函數的參數,並且array.length更長,因爲它將,作爲一個元素計數。 在DBNodejs Array將逗號作爲元素計算逗號

..."voteup": [ 5, 6, 7 ], "votedo": [ 5, 4, 6, 1, 8, 2, 7, 3 ]... 

在index.js

res.render('post', {vup: user.voteup, vdo: user.votedo, login: login} 
        ^this is the array^ 

在post.jade

script. 
     fixVotes("#{vdo}", "#{vup}"); 

在client.js

function fixVotes(down, up) { 
    console.log(up.length); //Is larger 
    for (var i = 0; i < up.length; i++) { 

     document.getElementById("upvote" + up[i]).className = "disabled"; 
     document.getElementById("updis" + up[i]).className = ""; 

    } 
    for (var i = 0; i < down.length; i++) { 

     document.getElementById("downvote" + down[i]).className = "disabled"; 
     document.getElementById("downdis" + down[i]).className = ""; 

    } 
} 
+1

聽起來像不夠逃脫,但我們無法看到您的代碼真正告訴。 – Bergi

回答

0

最有可能的,這個問題是因爲你在假設一個實際上數組是字符串格式的。請注意,您可以通過一個這樣的數組遍歷:

var voteup = [ 5, 6, 7 ]; 
 

 
for(var i = 0; i < voteup.length; i++) 
 
{ 
 
    console.log(i + ": " + voteup[i]); 
 
} 
 

但是如果你的陣列是字符串格式,那麼你可能會得到意外的輸出。請注意,for環路仍然可以工作,但輸出將在字符串的情況是不同的(我猜這是什麼在你的情況發生):

var voteup = "[ 5, 6, 7 ]"; 
 

 
for(var i = 0; i < voteup.length; i++) 
 
{ 
 
    console.log(i + ": " + voteup[i]); 
 
}

在這種情況下,如果你想要把它當作一個數組並打印元素,你只需要使用JSON.parse()首先將它轉換爲數組:

var voteupString = "[ 5, 6, 7 ]"; 
 
var voteup = JSON.parse(voteupString); 
 

 
for(var i = 0; i < voteup.length; i++) 
 
{ 
 
    console.log(i + ": " + voteup[i]); 
 
}