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?
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.
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.
Reflects the number of elements in an array. The prototype 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With