Associative arrays in JavaScript

Source: Internet
Author: User

The usual array is implicitly or displays the specified array subscript when it fills, but the array in JS can be assigned a value in the form of a name, which forms an associative array, such as:

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[

Notice the above alert (arr[0]); This sentence, it will return undifined. This means that, in an associative array, an array element cannot be accessed with the traditional subscript, and must pass through the name of the element.
This form of access to array elements by name has the advantage of being highly readable and flexible and convenient. To a certain extent, it can be used as a hash table in JS.
When iterating over an associative array, you need to use a for-in loop, noting two different traversal methods in the following code:

var arr=New  Array (); arr["China"]= "Beijing,niaoling,hulan"; arr["USA"]= " Newyork,washington,atlanta "; arr[" Japan "]=" Tokyo"//  This way you can traverse the name of the associative array for  (var in arr) {alert (item);} // this way you can iterate through the elements in the associative array  for (var in arr) {alert (Arr[item]);}

Associative arrays in JavaScript

Related Article

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.