Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 905
prinzdezibel Avatar asked May 17 '09 09:05

prinzdezibel


People also ask

How do you add properties to an array?

Arrays are objects and therefore you can add your own properties to them: var arr = [1, 2, 3]; arr. foo = 'bar'; Extending from other answers, here are the following ways of iterating over the array, excluding custom properties.

Can object property be an array?

Just as object properties can store values of any primitive data type (as well as an array or another object), so too can arrays consist of strings, numbers, booleans, objects, or even other arrays.

Which allows you to add properties and methods to an array or object?

Reflects the number of elements in an array. The prototype property allows you to add properties and methods to an object.

Which property allows you to add properties and methods to an object?

Prototype is used to add new properties and methods to an object. myobj: The name of the constructor function object you want to change. name: The name of the property or method to be created.


1 Answers

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.

like image 118
Paul Dixon Avatar answered Oct 17 '22 11:10

Paul Dixon