出于某种原因,我可以将JSON对象推送到我的数组“list”,但是当我调用它的.length时,似乎我得到的是字符数而不是项数。
更新:查看解决方案的答案。我的脚本没有返回字符,它正在以指数方式循环。
$.getJSON('[omitted].php?callback=?',function(d,item){
var list = []
alert('Length: '+d.length) // d consists of 271 JSON objects, d.length = 271
for (i=0;i<d.length;i++){
$.each(d,function(){ // for each JSON object we add...
list.push({'name':this.name,'href':this.href,'img':this.img})
})
if (i==d.length){
alert('Completed - Length: '+list.length) // list.length = 44711. Why?
}
}
})
请注意,当我使用alert(list)时,我看到:
[object,Object][object,Object][object,Object] ...
而不是数组:
[[object,Object][object,Object][object,Object] ... ]
答案 0 :(得分:2)
我相信这......
$.each(d,function(){
应该是这个......
$.each(d[i],function(){
否则,您为d
中的每个项目循环使用相同的d
结构。
答案 1 :(得分:1)
//Loop though d
for (i=0;i<d.length;i++){
//loop through d
$.each(d,function(){ // for each JSON object we add...
list.push({'name':this.name,'href':this.href,'img':this.img})
})
if (i==d.length){
alert('Completed - Length: '+list.length) // list.length = 44711. Why?
}
}
你看到了问题吗?
你基本上是这样做的:
var list = [];
for (var i=0;i<d.length;i++){
for (var j=0;j<d.length;j++){
list.push( {} );
}
}
答案 2 :(得分:1)
让我们看看,每个陈述的基本结构
$.each(mixedVar, function(index, item) {
//Here index, is not an array but singular item's index, so whenever
// index.length will be applied it will be taken as a variables, that a list/collection/array
});
同样,你的d
也会返回一个项目的索引,这是一个混合变量,既不是列表也不是数组。