Jun. 16th, 2013

webdev: (Default)
It doesn’t. JavaScript arrays on numeric indices only. You can push anything you want into an array, including objects, which is nice.

JavaScript arrays are also objects, so they can have properties like objects. And JavaScript has overloaded its square bracket notation so that square brackets not only refer to array members, but also to properties on objects. Thus:
var myObj = {}; 
myObj.newProp = 4;
console.log(myObj[newProp]); // will output a reference error because newProp (no quotes) is undefined
console.log(myObj[‘newProp’]); // will output 4 on the console.

That’s covered in the ECMA standard, section 11.2.1:
11.2.1 Property Accessors
Properties are accessed by name, using either the dot notation:
MemberExpression . IdentifierName
CallExpression . IdentifierName
or the bracket notation:
MemberExpression [ Expression ]
CallExpression [ Expression ]

You can add all of the properties you want to arrays (I do it all the time) but a property on an array is not a member of that array. That means a property has no index in the array, and cannot be searched for using methods like indexOf. Thus:
var myObj = {};
var myArray = [‘apples’, ‘oranges’, ‘lemons’, ‘pluots’];
console.log(myArray.length); // will output 4 on the console.
myArray.newProp = myObj;  // newProp is now a property on myArray.
console.log(myArray.newProp === myArray[‘newProp’]); // will output true.
console.log(myArray.length); // will output 4 on the console.
console.log(myArray.indexOf(‘newProp’)); // will output -1, because newProp is not a member of the array, it is a property.