使用属性名称的变量创建对象 [英] create object using variables for property name
问题描述
是否可以在对象文字属性中使用变量名进行对象创建?
Is it at all possible to use variable names in object literal properties for object creation?
示例
function createJSON (propertyName){
return { propertyName : "Value"};
}
var myObject = createJSON("myProperty");
console.log(myObject.popertyName); // prints "value"
console.log(myObject.myProperty); // Does not exist
推荐答案
如果,在ES6中,你想要为属性名称使用变量,可以使用新的ComputedPropertyName语法。将变量名放在方括号之间:
If, in ES6, you want to use a variable for a property name, you can use the new ComputedPropertyName syntax. Place the variable name between square brackets:
var foo = "bar";
var ob = { [foo]: "something" }; // ob.bar === "something"
在ES5中,你必须先创建对象,然后使用方括号表示法添加属性。
In ES5, you have to create the object first, and then add the property using square bracket notation.
var foo = "bar";
var ob = {};
ob[foo] = "something"; // === ob.bar = "something"
如果你想以编程方式创建JSON,那么你必须将对象序列化为符合JSON格式的字符串。例如使用 JSON.stringify
方法。
If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify
method.
这篇关于使用属性名称的变量创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!