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.
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
index = ['hello world']or[1,2]?.toString()of an array is.join()a[1]isa['1']isa[['1'].join(',')]isa[String(['1'])]isa[['1']]isa[[1]].var a = [1, 2, 3] var index = [1, 2] console.log(a[index]);