Home > Article > Web Front-end > About associative array analysis in JavaScript_Basic knowledge
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:
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:
//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]);
}