6

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

Hate Names
  • 1,596
  • 1
  • 13
  • 20
  • 3
    It's not an array, it's an object. – JJJ Aug 04 '13 at 18:07
  • 2
    @Juhana: I *could* be an Array, but [it should not](http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/) – Bergi Aug 04 '13 at 18:10

1 Answers1

6

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.

rid
  • 61,078
  • 31
  • 152
  • 193
  • Woot, thank you. exactly what I needed, sorry for the trouble – Hate Names Aug 04 '13 at 18:10
  • @rid it might be better to do `Object.prototype.hasOwnProperty.call(array, key)` just in case `array` has a property `hasOwnProperty` – Paul S. Aug 04 '13 at 18:16
  • @PaulS., well, there are quite a few more edge cases, but they're all handled by [Mozilla's polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Compatibility). Answer updated. – rid Aug 04 '13 at 18:18