The _javascript technique of JS associative array indexed by object

Source: Internet
Author: User
For JSON objects, you can refer to Wikipedia (Http://zh.wikipedia.org/zh-cn/JSON) and the official website (http://www.json.org/json-zh.html).

We often say that JavaScript native supports JSON, because we can think of JSON as a flexible application of JavaScript object objects.

Typically, we use JSON in the form of data interchange in the front and back table:

In code logic, however, more is the way of associative arrays. But even then, we rarely use object types as key-value pairs.

var a= {}, b= [];

A[B] = new Date (); The time value can be obtained by a[b].

  The type of the key name can be an object , what a beautiful thing ah!

But there is one problem. If you want to use this, you need to have a condition: the data must be dynamically added. (currently in classmate this, there is no condition to test other browsers, currently tested IE8 and Sogou browser's IE kernel and weikit kernel)

The test code is as follows:

Copy Code code as follows:

var d = document.getElementById ("Hello"), obj = [1,2,3], a = {obj: "Test"};
A[d] = "DomElement";
Alert (A[obj]); Undefined
Alert (A[d]); DomElement
Alert (A[document.getelementbyid ("Hello")]); DomElement
A[obj] = "Array Object";
Alert (A[obj]); Array Object


In fact, the key name is a string:
Copy Code code as follows:

var d = document.getElementById ("Hello"), obj = [1,2,3], a = {obj: "Test"};
Alert (a["obj"]); Test

var str = new String ("1,2,3");
A[obj] = "Array Object";
Alert (A[obj]); Array Object
Alert (A[str]); Array Object

var Class1 = function (_val) {
var val = _val;
this.tostring = function () {
return Val;
}
}

var obj2 = new Class1 ("1,2,3");
Alert (A[obj2]);//array Object

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.