简体   繁体   English

在javascript中通过具有多个“节点”的变量访问对象属性

[英]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.

相关问题 (JavaScript)是否可以为一个变量定义多个属性? - (Javascript) Is there a way to define more than one property to a variable? 如何匹配 object 的多个属性 - How to match more than one property of an object 您可以在 Javascript 中使用一行代码更改多个变量的相同属性吗? - Can you change the same property for more than one variable with one line of code in Javascript? 如何在JavaScript中发布多个变量? - How post more than one variable in javascript? 在javascript中,在for循环中声明多个变量 - in javascript, declare more than one variable in for loop javascript函数中有多个变量? - More than one variable in a javascript function? 如何在JavaScript中传递多个参数来设置对象属性的属性? - How can I pass more than one argument to set attribute of object property in JavaScript? 如何过滤对象数组并检查数组内是否有多个 object 在 Javascript 中具有相同的属性值? - How to filter array of objects and check if more than one object inside the array has the same property value in Javascript? 无法访问javascript变量中的对象属性 - Can't access object property in javascript variable 具有多个变量的Angularjs ng-repeat过滤器属性? - Angularjs ng-repeat filter property with more than one variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM