Javascript 如何在javascript中将字符串转换为对象的字段名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4841254/
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
How to convert string as object's field name in javascript
提问by ywenbo
I have a js object like:
我有一个 js 对象,如:
obj = {
name: 'js',
age: 20
};
now i want to access name field of obj, but i can only get string 'name', so how to convert 'name' to obj's field name, then to get result like obj.name.
现在我想访问obj的name字段,但是我只能得到字符串'name',那么如何将'name'转换为obj的字段名,然后得到像obj.name这样的结果。
Thank you in advance.
先感谢您。
回答by Chandu
You can access the properties of javascript object using the index i.e.
您可以使用索引访问 javascript 对象的属性,即
var obj = {
name: 'js',
age: 20
};
var isSame = (obj["name"] == obj.name)
alert(isSame);
var nameIndex = "name"; // Now you can use nameIndex as an indexor of obj to get the value of property name.
isSame = (obj[nameIndex] == obj.name)
Check example@ : http://www.jsfiddle.net/W8EAr/
检查示例@:http: //www.jsfiddle.net/W8EAr/
回答by Mathieu Ravaux
In Javascript, obj.name
is equivalent to obj['name']
, which adds the necessary indirection.
在 Javascript 中,obj.name
相当于obj['name']
,增加了必要的间接性。
In your example:
在你的例子中:
var fieldName = 'name'
var obj = {
name: 'js',
age: 20
};
var value = obj[fieldName]; // 'js'
回答by Seldaek
It's quite simple, to access an object's value via a variable, you use square brackets:
很简单,要通过变量访问对象的值,您可以使用方括号:
var property = 'name';
var obj = {name: 'js'};
alert(obj[property]); // pops 'js'
回答by Alter Lagos
Not related at all, but for anyone trying to define object's field name from a string variable, you could try with:
根本不相关,但对于任何试图从字符串变量定义对象的字段名称的人,您可以尝试:
const field = 'asdf'
const obj = {[field]: 123}
document.body.innerHTML = obj.asdf
回答by Vitalii Fedorenko
As objects are associative arrays in javascript you can access the 'name' field as obj['name']
or obj[fieldName]
where fieldName = 'name'
.
由于对象是 javascript 中的关联数组,您可以访问 'name' 字段 asobj['name']
或obj[fieldName]
where fieldName = 'name'
。