12

Possible Duplicate:
In javascript how can we identify whether an object is a Hash or an Array?

In javascript

typeof([])

and

typeof({})

both return "object".

How can I reliably distinguish between an array and an associative array in Javascript?

I have thought of testing the object in question to see if it has the "length" attribute (indicating it would be an array), but what then the following would also be seen as an array:

{length:5}
Community
  • 1
  • 1
mydoghasworms
  • 18,233
  • 11
  • 61
  • 95

3 Answers3

16

Modern browsers have Array.isArray built in.

For older browsers, you can test for that function and add it when necessary.

if( typeof Array.isArray !== 'function' ) {
    Array.isArray = function( arr ) {
        return Object.prototype.toString.call( arr ) === '[object Array]';
    };
}

alert( Array.isArray( [] ) );

EDIT:

Array.isArray is part of ECMAScript 5:

15.4.3.2 Array.isArray ( arg )

The isArray function takes one argument arg, and returns the Boolean value true if the argument is an object whose class internal property is "Array"; otherwise it returns false. The following steps are taken:

  1. If Type(arg) is not Object, return false.
  2. If the value of the [[Class]] internal property of arg is "Array", then return true.
  3. Return false.
Community
  • 1
  • 1
user113716
  • 318,772
  • 63
  • 451
  • 440
5

A good idea is, to check for the internal [[CClass]] value. To do that, you need to invoke Object.prototype.toString:

var toStr = Object.prototype.toString;

toStr.call([]);  // === [object Array]
toStr.call({});  // === [object Object]
jAndy
  • 231,737
  • 57
  • 305
  • 359
0

Associative arrays do not exist in Javascript.

An array can only have numeric keys. If you access a string key, you are in fact using a shortcut, which is exactly equivalent to the object notation.

http://www.quirksmode.org/js/associative.html

http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/

Palantir
  • 23,820
  • 10
  • 76
  • 86
  • 5
    Erm, I think you've got that backwards. Normal JS objects are associative arrays. It is real arrays that do not exist in javascript. An Array in js is an object with sugar to make it look like a real array (most notable a length property, which just returns 1 + the highest numeric field stored in the object). – beldaz Mar 21 '12 at 09:53