April 14, 2012
Why is my array.length returning such a high number?
Question by Trey
For some reason I can push JSON objects to my array “list”, but when I call its .length, it seems that I’m getting the number of characters rather than number of items.
UPDATE: See answers for solution. My script wasn’t returning characters, it was looping through exponentially.
$.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?
}
}
})
Note that when I use alert(list) I see:
[object,Object][object,Object][object,Object] ...
Rather than an array:
[[object,Object][object,Object][object,Object] ... ]
Answer by am not i am
I believe this…
$.each(d,function(){
should be this…
$.each(d[i],function(){
Otherwise you’re looping over the same d
structure once for every item in d
.
Answer by Starx
Lets see, the basic structure of a each statement
$.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
});
In the same way, your d
is also returning a item’s index, which is a mixed variable, neither a list nor an array.