2012-04-14 54 views
1

出於某種原因,我可以將JSON對象推送到我的數組「列表」中,但是當我調用它的.length時,看起來我得到的是字符數而不是項數。爲什麼我的array.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(名單)我看到:

[object,Object][object,Object][object,Object] ... 

而不是一個數組:

[[object,Object][object,Object][object,Object] ... ] 
+0

[jsFiddle](http://jsfiddle.net),請問? (至於它沒有顯示爲數組,隱式連接字符是','。括號不會被添加。) – Ryan 2012-04-14 23:33:48

回答

2

我相信這...

$.each(d,function(){ 

應該是這個...

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

否則你遍歷相同d結構一旦爲每個項目在d

+0

社區wiki?爲什麼? – Ryan 2012-04-14 23:37:54

+0

@minitech:所以其他人會糾正我的錯誤。 ;) – 2012-04-14 23:38:18

+0

謝謝,所有的答案都非常有用。我會盡快趕上。 – Trey 2012-04-15 00:02:00

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({}); 
    } 
} 
+0

謝謝,所有的答案都非常有用。我會盡快趕上。 – Trey 2012-04-15 00:02:12

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也返回一個項目的索引,這是一個混合變量,既不是列表也不是數組。

+0

謝謝,所有的答案都非常有用。我會盡快趕上。 – Trey 2012-04-15 00:02:23