Index of array may be array by itself (tested in Chrome):
a = [1, 2, 3]
index = [1]
a[index] // returns 2
Is there any official documentation of this behavior?
Index of array may be array by itself (tested in Chrome):
a = [1, 2, 3]
index = [1]
a[index] // returns 2
Is there any official documentation of this behavior?
Is there any official documentation of this behavior?
12.3.2.1Runtime Semantics: Evaluation
defines the following 3 steps
3 Let propertyNameReference
be the result of evaluating Expression
.
4 Let propertyNameValue
be ? GetValue(propertyNameReference)
.
6 Let propertyKey
be ? ToPropertyKey(propertyNameValue)
.
Then 7.1.14ToPropertyKey ( argument )
is defined as
key
be ? ToPrimitive(argument, hint String)
.Type(key)
is Symbol
, thenkey
.ToString(key)
.Which effectively means, that unless the expression returns a Symbol
- it (the key) would be converted to a string.
As @Ryan and @4castle mentioned, javascript convert key
(inside []) to string using [].join(',')
.
You can test it in this snippet.
var abc = {
"1,2": "ddd"
};
console.log(abc[[1,2]]);
a[index]
will do a toString on the index, and since index is an array, its to string is index.join()
making the output a['1']
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors