【问题标题】:Why is my array.length returning such a high number?为什么我的 array.length 返回这么高的数字?
【发布时间】:2012-04-26 20:16:57
【问题描述】:

出于某种原因,我可以将 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] ... ]

【问题讨论】:

  • jsFiddle,好吗? (至于不显示为数组,隐式连接字符为,,不加括号。)

标签: javascript jquery arrays string


【解决方案1】:

我相信这个...

$.each(d,function(){

应该是这个……

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

否则,您将为d 中的每个项目循环一次相同的d 结构。

【讨论】:

  • 谢谢,所有答案都非常有用。我会尽快投票。
【解决方案2】:
//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( {} );
    }
}

【讨论】:

  • 谢谢,所有答案都非常有用。我会尽快投票。
【解决方案3】:

让我们看看每个语句的基本结构

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

【讨论】:

  • 谢谢,所有答案都非常有用。我会尽快投票。
猜你喜欢
  • 2020-08-03
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多