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

后端 未结 3 413
走了就别回头了
走了就别回头了 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:09

    I think it come from 2 facts :

    1. The JS engine type as it goes
    2. any JS object can be access "like" an array

    so your

    ["a"] 
    

    when used as a key will be "casted" to string, which give

    a
    

    Even

    [[[[["a"]]]]].toString() == a // true
    

    so your

    x[y] 
    

    end un as

    x["a"]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-18 01:26

    Property names have to be strings. If you try to use an array as a property name, it gets its toString() method called implicitly. That generates a string containing a comma-separated list of its values.

    > var array = ['a', 'b', 'c'];
    undefined
    > array.toString();
    'a,b,c'
    

    If you only have one value, then there aren't any commas.

    > var array = ['a'];
    undefined
    > array.toString();
    'a'
    
    0 讨论(0)
提交回复
热议问题