Home  >  Article  >  Web Front-end  >  js associative array indexed by object_javascript skills

js associative array indexed by object_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:23:52989browse

Regarding 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 natively supports json, because we can think of json as a flexible application of JavaScript’s Object object.

Usually we use json, which is mainly used as the format for front-end and back-end data exchange:

In code logic, associative arrays are more commonly used. But even then we rarely use object types as the keys of key-value pairs.

 var a= {}, b= [];

 a[b] = new Date(); //The time value can be obtained through a[b].

 The type of key name can be object, what a wonderful thing!

But there is a problem. If you want to use it this way, there is a condition: the data must be added dynamically. (Currently, I am with my classmates and have no conditions to test other browsers. Currently, I have tested IE8 and the IE kernel and weikit kernel of Sogou browser)

The test code is as follows:

Copy code The 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, the key names are all strings:
Copy code The 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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn