Search code examples
javascriptarrayskey

How to iterate array keys in Javascript?


I have an array created with this code:

var widthRange = new Array();
widthRange[46] = { min:0,  max:52 };
widthRange[66] = { min:52, max:70 };
widthRange[90] = { min:70, max:94 };

I want to get each of the values 46, 66, 90 in a loop. I tried for (var key in widthRange) but this gives me a whole bunch of extra properties (I assume they are functions on the object). I can't use a regular for loop since the values are not sequential.


Solution

  • You need to call the hasOwnProperty function to check whether the property is actually defined on the object itself (as opposed to its prototype), like this:

    for (var key in widthRange) {
        if (key === 'length' || !widthRange.hasOwnProperty(key)) continue;
        var value = widthRange[key];
    }
    

    Note that you need a separate check for length.
    However, you shouldn't be using an array here at all; you should use a regular object. All Javascript objects function as associative arrays.

    For example:

    var widthRange = { };  //Or new Object()
    widthRange[46] = { sel:46, min:0,  max:52 };
    widthRange[66] = { sel:66, min:52, max:70 };
    widthRange[90] = { sel:90, min:70, max:94 };