Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  91] [ 2]  / answers: 1 / hits: 22083  / 14 Years ago, sat, february 19, 2011, 12:00:00

Are arrays merely objects in disguise? Why/why not? In what way(s) are they (such/not)?



I have always thought of arrays and objects in JS as essentially the same, primarily because accessing them is identical.



var obj = {'I': 'me'};
var arr = new Array();
arr['you'] = 'them';

console.log(obj.I);
console.log(arr.you);
console.log(obj['I']);
console.log(arr['you']);


Am I mislead/mistaken/wrong? What do I need to know about JS literals, primitives, and strings/objects/arrays/etc...?



Are arrays/objects merely strings in disguise? Why/why not? In what way(s) are they (such/not)?


More From » arrays

 Answers
17

Arrays are objects.


However, unlike regular objects, arrays have certain special features.



  1. Arrays have an additional object in their prototype chain - namely Array.prototype. This object contains so-called Array methods which can be called on array instances. (List of methods is here: http://es5.github.io/#x15.4.4)



  2. Arrays have a length property (which is live, ergo, it auto-updates) (Read here: http://es5.github.io/#x15.4.5.2)



  3. Arrays have a special algorithm regarding defining new properties (Read here: http://es5.github.io/#x15.4.5.1). If you set a new property to an array and that property's name is a sting which can be coerced to an integer number (like '1', '2', '3', etc.) then the special algorithm applies (it is defined on p. 123 in the spec)




Other than these 3 things, arrays are just like regular objects.


Read about arrays in the spec: http://es5.github.io/#x15.4


[#93673] Thursday, February 17, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradford

Total Points: 709
Total Questions: 117
Total Answers: 91

Location: Sao Tome and Principe
Member since Wed, Dec 21, 2022
1 Year ago
;