1

出于某种原因,我可以将 JSON 对象推送到我的数组“列表”,但是当我调用它的 .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] ... ]
4

3 回答 3

2

我相信这...

$.each(d,function(){

应该是这个……

$.each(d[i],function(){

否则,d对于d.

于 2012-04-14T23:35:19.620 回答
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( {} );
    }
}
于 2012-04-14T23:35:36.650 回答
1

让我们看看 each 语句的基本结构

$.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还返回一个项目的索引,它是一个混合变量,既不是列表也不是数组。

于 2012-04-14T23:43:28.600 回答