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.

    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...
        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…


should be this…


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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!