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?

5
  • 1
    but what if index = ['hello world'] or [1,2]? Commented Nov 15, 2017 at 3:08
  • 3
    The subscript operator converts its argument to a string, and the .toString() of an array is .join() Commented Nov 15, 2017 at 3:10
  • 1
    a[1] is a['1'] is a[['1'].join(',')] is a[String(['1'])] is a[['1']] is a[[1]]. Commented Nov 15, 2017 at 3:11
  • 1
    Try this. What result do you get? var a = [1, 2, 3] var index = [1, 2] console.log(a[index]); Commented Nov 15, 2017 at 3:12
  • This is one of the bad parts. Commented Nov 15, 2017 at 3:18

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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]]);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.