Detailed discussion on the difference between array of array and object of object in js

  • 2021-07-24 09:33:11
  • OfStack

• object type:

How to create:


/*new  Operator Object Constructor */ 
var person = new Object(); 
person.name = "lpove"; 
person.age = 21; 
/* Or use the literal method of objects */ 
var person = { 
name: "lpove"; 
age : 21; 
}

• ES 7EN type

How to create:


`var colors = new Array( " red " , " blue " , " yellow " );

Differences and incomprehension

For example, there is an array a= [1, 2, 3, 4], and an object a= {0: 1, 1: 2, 2: 3, 3: 4}, and then you run alert (a [1]), and the result is the same in both cases! That is to say, data collections can be represented by either arrays or objects, so which one should I use?

I learned later that arrays represent collections of ordered data, while objects represent collections of unordered data. If the order of data is important, use arrays, otherwise use objects.

Of course, another difference between arrays and objects is that the data of arrays does not have a "name" (name), but the data of objects has a "name" (name).

But the problem is that in many programming languages, there is something called "associative array" (associative array). The data in this array has a name.

However, in "javascript DOM", we are not recommended to use associative arrays;

Associative arrays:


var lpove = Array(); 
lpove[name] = "lei"; 
lpove[age] = 21; 
lpove[living] = true;
/* Object construction */
  var lpove = Object();
    lpove.name = "lei";
    lpove.age = 21;
    lpove.living = true;

Because the nature of the associative array you create is essentially the property of the Array object


Related articles: