Why does accessing an element in an object using an array as a key work?

后端 未结 3 415
走了就别回头了
走了就别回头了 2021-01-18 00:41

What do you make of this?

var x = {a: 1};         //=> {a: 1}
var y = Object.keys(x); //=> [\'a\']
x[y]                    //=> 1

3条回答
  •  不思量自难忘°
    2021-01-18 01:15

    @Quentin suggests that property names are automatically converted to strings. Ok, I think he's onto something there, but giving two explicit arr.toString() examples doesn't really demonstrate accessing the property of an object using an array. I offered this as an edit to his post. However, he rolled it back.

    Anyway, this demonstrates the implicit behavior much more evidently, imo.

    var x = {'a,b,c': 1};
    
    var y = ['a','b','c'];
    
    x[y]; //=> 1
    

提交回复
热议问题