3

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?

dhilt
  • 18,707
  • 8
  • 70
  • 85
gshilin
  • 647
  • 14
  • 23

3 Answers3

4

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

  1. Let key be ? ToPrimitive(argument, hint String).
  2. If Type(key) is Symbol, then
    a. Return key.
  3. Return ! ToString(key).

Which effectively means, that unless the expression returns a Symbol - it (the key) would be converted to a string.

zerkms
  • 249,484
  • 69
  • 436
  • 539
3

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]]);
HerrGanzorig
  • 51
  • 1
  • 14
1

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

Davi DeBarros
  • 368
  • 1
  • 9