Home  >  Article  >  Web Front-end  >  About associative array analysis in JavaScript_Basic knowledge

About associative array analysis in JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:37:47903browse

Usual arrays will implicitly or explicitly specify the array subscript when filling, but arrays in JS can assign values ​​to elements in the form of names, which forms an associative array, such as:

Copy code The code is as follows:

var arr=new Array();
arr ["china"]="beijing,niaoling,hulan";
arr["usa"]="newyork,washington,atlanta";
arr["japan"]="tokyo";

alert(arr["china"]);
alert(arr["japan"]);

alert(arr[0]);

Pay attention to the sentence alert(arr[0]); above, it will return undiffed. This means that in an associative array, array elements can no longer be accessed through traditional subscripting but must be accessed through the element's name.
This form of accessing array elements by name has the advantages of high readability, flexibility and convenience. To a certain extent it can be used as a hash table in JS.
When traversing an associative array, you need to use a for in loop. Pay attention to the two different traversal methods in the following code:

Copy code The code is as follows:

var arr=new Array();
arr ["china"]="beijing,niaoling,hulan";
arr["usa"]="newyork,washington,atlanta";
arr["japan"]="tokyo";

//This way you can traverse the names in the associative array
for(var item in arr){
alert(item);
}

// This method can traverse each element in the associative array
for(var item in arr){
alert(arr[item]);
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn