JavaScript 对象:通过名称作为字符串访问变量属性
如果我有一个如下所示的 JavaScript 对象
var columns = {
left: true,
center : false,
right : false
}
,并且有一个传递该对象和属性名称的函数,那么
//should return false
var side = read_prop(columns, 'right');
read_prop(object, property)
的主体会是什么样子?
If I have a javascript object that looks like below
var columns = {
left: true,
center : false,
right : false
}
and I have a function that is passed both the object, and a property name like so
//should return false
var side = read_prop(columns, 'right');
what would the body of read_prop(object, property)
look like?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要它的函数 - 只需使用 括号表示法:
这等于点符号,
var side = columns.right;
,除了right
当使用括号表示法时,也可以来自变量、函数返回值等。如果您需要一个函数,这里是:
为了回答下面一些与原始问题没有直接关系的评论,可以通过多个括号引用嵌套对象。如果您有像这样的嵌套对象:
您可以按如下方式访问
c
的属性x
:如果属性未定义,则尝试引用它将返回
undefined
(不是null
或false
):You don't need a function for it - simply use the bracket notation:
This is equal to dot notation,
var side = columns.right;
, except the fact thatright
could also come from a variable, function return value, etc., when using bracket notation.If you NEED a function for it, here it is:
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
you can access property
x
ofc
as follows:If a property is undefined, an attempt to reference it will return
undefined
(notnull
orfalse
):ThiefMaster 的答案是 100% 正确的,尽管我遇到了类似的问题,我需要从嵌套对象(对象内的对象)中获取属性,因此作为他的答案的替代方案,您可以创建一个递归解决方案,该解决方案将允许您定义一个命名法来获取任何属性,无论深度如何:
对给定属性的字符串引用类似于
property1.property2
中的代码和注释 JsFiddle.
ThiefMaster's answer is 100% correct, although I came across a similar problem where I needed to fetch a property from a nested object (object within an object), so as an alternative to his answer, you can create a recursive solution that will allow you to define a nomenclature to grab any property, regardless of depth:
Where your string reference to a given property ressembles
property1.property2
Code and comments in JsFiddle.
由于上面的答案对我的项目有所帮助(我问了一个重复的问题并在此处引用),因此我在嵌套在 var 中时提交了一个括号表示法的答案(我的测试代码):
Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var: