Home > Article > Web Front-end > What is the difference between javascript objects and arrays
Difference: Difference: 1. An object is an unordered collection containing named values, while an array is an ordered collection containing encoded values. 2. The data of the array has no name, only subscripts, while the data of the object needs to specify a name.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Object (Object) and Array (Array) in JavaScript sometimes look similar, but they are two different types of data collections. An object is an unordered collection containing named values, and An array is an ordered collection of encoded values.
Example 1
The following example uses objects and arrays to store the two values of 1 and true respectively. The code structure is as follows:
var o = { //对象 x :1, //该值命名为x y : true //该值命名为y } var a = [ //数组 1, //该值隐含编码为0 true //该值隐含编码为1 ]
The storage form of the object is very much like an array, so it is called an associative array, but it is not an array in the true sense. Associative arrays associate values with specific strings. A real array is not associated with a string, but it is associated with a value and a non-negative integer subscript.
console.log(o["x"]); //返回1,使用点语法存取属性 console.log(a[0]); //返回1,使用中括号存取属性
When using dot syntax to access attributes, the attribute name is an identifier; when using square brackets to access attributes, the attribute name is a string.
Example 2
When using the dot operator to access object properties, the property name is represented by an identifier; when using square brackets to access the object Attribute, the attribute name is represented by a string, so the string can be dynamically generated during runtime.
var o = { p1 : 1, p2 : true } for (var i = 1; i < 3; i ++) { console.log(o["p" + i]); }
Accessing object properties with string expressions through the associative array method is very flexible. When there are many object properties, it will be troublesome to use dot syntax to access object properties. In addition, in some special cases, only associative arrays can be used to access object properties.
[Related recommendations: javascript learning tutorial]
The above is the detailed content of What is the difference between javascript objects and arrays. For more information, please follow other related articles on the PHP Chinese website!