Js associated array indexed by Object

Source: Internet
Author: User

For more information about JSON objects, see wikipedia (http://zh.wikipedia.org/zh-cn/JSON) and the official website (http://www.json.org/json-zh.html ).

We often say that JavaScript supports json native, because json is a flexible application of JavaScript Object.

Generally, we use json as the format for data exchange between the front and back ends:

In the Code logic, more is the method of associating arrays. Even so, we seldom use the object type as the key name of the key-value pair.

Var a = {}, B = [];

A [B] = new Date (); // the time value can be obtained through a [B.

  The type of the key name can be an object.What a wonderful thing!

But there is a problem. If you want to use this method, you need to have a condition that the data must be dynamically added.(Currently, students have no conditions to test other browsers. Currently, IE8, sogou browser's IE kernel and weikit kernel are tested)

The test code is as follows:

Copy codeThe Code is 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, all key names are strings:Copy codeThe Code is 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.