JavaScript 对象:按名称作为字符串访问变量属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4255472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript object: access variable property by name as string
提问by Hailwood
If I have a javascript object that looks like below
如果我有一个如下所示的 javascript 对象
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?
的身体read_prop(object, property)
会是什么样子?
回答by ThiefMaster
You don't need a function for it - simply use the bracket notation:
您不需要它的函数 - 只需使用括号表示法:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
这与点表示法, 相同var side = columns.right;
,但right
在使用括号表示法时,它也可能来自变量、函数返回值等。
If you NEED a function for it, here it is:
如果你需要一个函数,这里是:
function read_prop(obj, prop) {
return obj[prop];
}
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:
要回答下面的一些与原始问题没有直接关系的评论,可以通过多个括号引用嵌套对象。如果你有一个像这样的嵌套对象:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
您可以访问财产x
的c
,如下所示:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
如果属性未定义,则尝试引用它会返回undefined
(notnull
或false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
回答by Prusprus
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:
ThiefMaster 的答案是 100% 正确的,尽管我遇到了类似的问题,我需要从嵌套对象(对象内的对象)中获取属性,因此作为他答案的替代方案,您可以创建一个递归解决方案,让您定义一个命名法来获取任何属性,无论深度如何:
function fetchFromObject(obj, prop) {
if(typeof obj === 'undefined') {
return false;
}
var _index = prop.indexOf('.')
if(_index > -1) {
return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
}
return obj[prop];
}
Where your string reference to a given property ressembles property1.property2
您对给定属性的字符串引用类似于 property1.property2
Code and comments in JsFiddle.
JsFiddle 中的代码和注释。
回答by Junco
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:
由于上面的答案对我的项目有所帮助(我问了一个重复的问题并在此处被引用),因此我在 var 中嵌套时提交了括号表示法的答案(我的测试代码):
<html>
<head>
<script type="text/javascript">
function displayFile(whatOption, whatColor) {
var Test01 = {
rectangle: {
red: "RectangleRedFile",
blue: "RectangleBlueFile"
},
square: {
red: "SquareRedFile",
blue: "SquareBlueFile"
}
};
var filename = Test01[whatOption][whatColor];
alert(filename);
}
</script>
</head>
<body>
<p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>
<br/>
<p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>
<br/>
<p onclick="displayFile('square', 'red')">[ Sq Red ]</p>
</body>
</html>