为什么使用数组作为键来访问对象中的元素? [英] Why does accessing an element in an object using an array as a key work?
问题描述
您对此有何看法?
var x = {a: 1}; //=> {a: 1}
var y = Object.keys(x); //=> ['a']
x[y] //=> 1
如果 y = ['a']
,则 x [y]
与执行 x [['a']]
相同,对吧?
if y = ['a']
, x[y]
is the same as doing x[['a']]
, right?
x[['a']]; //=> 1
x[[['a']]]; //=> 1
x[[[[[[[['a']]]]]]]]; //=> 1
有人可以解释这里发生了什么吗?为什么这样做有效?
Can someone explain what's happening here? Why does this work?
推荐答案
@Quentin建议将属性名称自动转换为字符串.好的,我认为他在这里,但是给出两个显式的 arr.toString()
示例并没有真正演示如何使用数组访问对象的属性.我将此内容作为对他帖子的修改.但是,他回滚了.
@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.
无论如何,这更明显地证明了隐式行为,imo.
Anyway, this demonstrates the implicit behavior much more evidently, imo.
var x = {'a,b,c': 1};
var y = ['a','b','c'];
x[y]; //=> 1
这篇关于为什么使用数组作为键来访问对象中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!