Getting the length of a 'named' array?

javascript

Solution

You could use `Object.keys()` to obtain an array of keys, then count them:

Object.keys(array).length

Or, if you're targeting ECMAScript 3 or otherwise don't have `Object.keys()`, then you can count the keys manually:

var length = 0;
for (var key in array) {
    if (array.hasOwnProperty(key)) {
        ++length;
    }
}

There are a few edge cases with this approach though, depending on the browsers you're targeting, so using Mozilla's polyfill for `Object.keys()` instead might be a good idea.

Problem

I'm not sure what they are called, but what I mean is this: ``` array["water"] = 50; array["fire"] = 30; ``` length should be 2 here how can I see how many attributes I have in the array? array.length doesn't work =( I've been trying all kinds of things and I feel like I'm missing something really simple here.. Thank you for your help

Original source

Related problems