SoFunction
Updated on 2025-03-04

JavaScript Associative array indexed by objects

Regarding JSON objects, you can refer to wikipedia (/zh-cn/JSON), and the official website (/)。

We often say that JavaScript natively supports json, because we can think that json is a flexible application of JavaScript Object objects.

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

In code logic, it is more about associative arrays. But even so, we rarely use object types as key names for key-value pairs.
var a= {}, b= [];
a[b] = new Date(); //The time value can be obtained through a[b].

Key nameThe type can be an objectWhat a wonderful thing!

But there is one problem. If you want to use this, you need to have a condition: the data must be added dynamically. (Currently, there are no conditions to test other browsers. Currently, IE8 and Sogou browsers IE kernel and weikit kernel)

The test code is as follows:

Copy the codeThe code is as follows:

var d = ("hello"), obj = [1,2,3], a = {obj:"test"};
a[d] = "DOMElement";
alert(a[obj]); //undefined
alert(a[d]);//DOMElement
a[obj] = "Array Object";
alert(a[obj]);//Array Object