Warm tip: This article is reproduced from stackoverflow.com, please click
arrays javascript object javascript-objects

Why can I add named properties to an array as if it were an object?

发布于 2020-03-27 15:43:33

The following two different code snippets seem equivalent to me:

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

and

var myObject = {'A': 'Athens', 'B':'Berlin'};

because they both behave the same, and also typeof(myArray) == typeof(myObjects) (both yield 'object').

Is there any difference between these variants?

Questioner
prinzdezibel
Viewed
36
Paul Dixon 2009-05-17 17:44

Virtually everything in javascript is an object, so you can "abuse" an Array object by setting arbitrary properties on it. This should be considered harmful though. Arrays are for numerically indexed data - for non-numeric keys, use an Object.

Here's a more concrete example why non-numeric keys don't "fit" an Array:

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

alert(myArray.length);

This won't display '2', but '0' - effectively, no elements have been added to the array, just some new properties added to the array object.