Syntax for creating composite key objects in JavaScript

Is there any syntax for passing compound keys, i.e. lists and objects,
like the example below, or is it a design?

> obj = {[1, 2]: 3};
SyntaxError: Unexpected token [

The second example works fine, it's not bad, but I would like to know if there is an alternative way.

> obj = {};
> obj[[1, 2]] = 3;
3
> [1, 2] in obj;
> true
+5
source share
2 answers

The object property names in JavaScript are at the end of the line, your second example seems to work because the parenthesis property accessory converts the expression [1, 2]to String(return "1,2"), for example:

var obj = {};
obj[[1, 2]] = 3;

console.log(obj["1,2"]); // 3

Another example:

var foo = { toString: function () { return "bar"; } },
    obj = {};

obj[foo] = 3; // foo is converted to String ("bar")
console.log(obj["bar"]); // 3

See also:

+10
source

[1, 2] ? ? " ", , , , , .

[1, 2] , :

var obj = {  
  "[1, 2]": 3
}

, , [1, 2] .

+1

All Articles