[英]access object property by variable with more than one “nodes” in javascript
Imagine this object: 想象一下这个对象:
var obj = {
one: {
two:{
three: "whatever"
}
}
}
If I want to access "whatever" I simply do: 如果我想访问“任何内容”,则只需执行以下操作:
console.log( obj.one.two.three ) --> "whatever"
And I can even use a variable like: 而且我什至可以使用像这样的变量:
var one = "one"
console.log( obj[one].two.three ) --> "whatever"
But why doesn't this work ? 但是为什么不起作用呢?
var onetwo = "one.two"
console.log( obj[onetwo].three ) --> undefined
But why doesn't this work ?
但是为什么不起作用呢?
Because the notation is not supported in the language. 因为该语言不支持该表示法。 It's simply not there.
根本不在那里。 The specification defines property access as with bracket notation as:
该规范将属性访问定义为括号表示法 :
MemberExpression [ Expression ]
MemberExpression [表达式]
The algorithm for defining how that works is defined in the lines below, the syntax for nested properties is simply not a part of the core language syntax. 下面几行中定义了定义工作方式的算法,嵌套属性的语法根本不是核心语言语法的一部分。
There are specific parsers that let you do this, and you can always invoke the language compiler yourself (JS lets you do that with eval
for example - don't though), but the use case is not common enough. 有特定的解析器使您可以执行此操作,并且您始终可以自己调用语言编译器(例如,JS使您可以通过
eval
进行此操作-可以),但是用例并不足够普遍。
Note: Since you mentioned in the comments you use Angular, it already has that built in using $parse
doing var res = $parse("one.two.three")(obj);
注意:自从您在注释中提到使用Angular以来,它已经使用
$parse
内置了此功能,而var res = $parse("one.two.three")(obj);
Here's a fiddle. 这是一个小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.