Associative array problem in JavaScript

  • 2020-05-10 17:44:06
  • OfStack


var beatles = ["john","Paul","George","Ringo"];

The beatles array above is a classic example of a traditional array: each element is subscripted with a number, and each element is incremented by one. The index of the first element is 0, and the index of the second element is 1. And so on.

If only the values of the elements are given when the array is filled, the array will be a traditional array, and the subscripts of its elements will be automatically created and refreshed.

You can change this default behavior by explicitly subscripting each new element as it fills the array. When subscripting a new element, you don't have to limit yourself to integer Numbers. You can also use strings:


var lennon = Array();
lennon["name"]    = "John";
lennon["year"]    = "1940";
lennon["living"]    = false;

Such arrays are called associative arrays. The code is more readable because you can use strings instead of numeric values. However, this usage is not a good habit and is not recommended. Essentially, when you create an associative array, you're creating properties of the Array object. In JavaScript, all variables are actually objects of some type. For example, a Boolean is an object of type Boolean, and an array is an object of type Array. In the example above, you're actually adding name, year, and living to the lennon array. Ideally, you should not modify the properties of Array objects, but instead use generic objects (Object).

That's all for this article, I hope you enjoy it.


Related articles: