Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  76] [ 1]  / answers: 1 / hits: 70617  / 15 Years ago, sun, may 17, 2009, 12:00:00

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?


More From » arrays

 Answers
8

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.


[#99518] Wednesday, May 13, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
;