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

About associative array analysis in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 17:37:47
Original
928 people have browsed it

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]);
}

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template