我将两个数组从我的mongodb传递到我的快速服务器,然后进入我的玉模板。在这个模板上,数组进入我的client.js javascript函数的参数,并且array.length更长,因为它将,
计为元素。
在db
..."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 = "";
}
}
答案 0 :(得分: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] );
}