How to get array keys in Javascript?
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 };
The stringified keys can be queried with Object.keys(array)
.
If you are doing any kind of array/collection manipulation or inspection I highly recommend using Underscore.js. It's small, well-tested and will save you days/weeks/years of javascript headache. Here is its keys function:
Keys
Retrieve all the names of the object's properties.
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]