About associative array analysis in JavaScript _ basics

Source: Internet
Author: User

The usual array is populated with an implicit or display of the specified array subscript, but the array in JS can be assigned the element in the form of a name, which forms an associative array, such as:

Copy Code code as follows:

var arr=new Array ();
arr["]=" and "Beijing,niaoling,hulan";
arr["USA"]= "Newyork,washington,atlanta";
arr["Japan"]= "Tokyo";

Alert (arr["a");
Alert (arr["Japan"]);

Alert (arr[0]);

Note the above alert (arr[0]); This sentence, it will return to undifined. This means that, in an associative array, you can no longer access an array element in a traditional subscript way and must pass the element's name.
This type of access to array elements by name has the advantage of readability, flexibility and convenience. To some extent, it can be used as a hash table in JS.
When traversing an associative array, you need to use a for in loop, and notice two different ways to traverse the following code:

Copy Code code as follows:

var arr=new Array ();
arr["]=" and "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 way you can iterate through the elements in an associative array
For (var item in arr) {
Alert (Arr[item]);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.