Javascript arrays and dictionaries

Javascript array Array, is both an array, also a dictionary (Dictionary).

First example look at the usage of the array.

Javascript code   Collection Code
  1. var a = new Array();  
  2. a[0] = "Acer";  
  3. a[1] = "Dell";  
  4. for (var i in a) {  
  5.     alert(i);          
  6. }  


The above code is the creation of an array, each element is a string object.

Then traverse the array. Note that the result is 0 and i is 1, a [i] The result was a string.

This is very like the one on the property traverse the object of it comes in.

 

Here's look at the use of the dictionary.

Javascript code   Collection Code
  1. var computer_price = new Array();  
  2. computer_price["Acer"] = 500;  
  3. computer_price["Dell"] = 600;  
  4. alert(computer_price["Acer"]);  

We even like above can also traverse the array (dictionary)

Javascript code   Collection Code
  1. for (var i in computer_price) {  
  2.     alert(i + ": " + computer_price[i]);  
  3. }  

where i is the key for each dictionary. The output is:

Acer: 500

Dell: 600

 

Below, a look at the interesting thing about Javascript, or the above examples.

We can computer_price as a dictionary object, but it is a key value of each property.

That is a property computer_price of Acer. We can use it like this: computer_price.Acer

 

Next, look at ways to simplify the statement dictionaries and arrays.

Javascript code   Collection Code
  1. Array = var [. 1, 2,. 3];  // Array  
  2. var array2 = { "Acer": 500, "Dell": 600 }; // 字典  
  3. alert(array2.Acer); // 50  


Such statements and the dictionary is in front of the same. In our example, Acer is key, but also as an attribute of the object dictionary.

Reproduced in: https: //www.cnblogs.com/kungfupanda/p/4062657.html

Guess you like

Origin blog.csdn.net/weixin_33950035/article/details/94493428