[英]How to create javascript object with custom name?
It's a little bit difficult to explain what I need, so I'll use some non-working code: 解释我需要什么有点困难,所以我会使用一些非工作代码:
function createSimpleObjet(name, value){
return {
name: value
};
}
//create it
var obj = createSimpleObject('Message', 'Hello World!');
//test it:
alert(ojb.Message); //should alert 'Hello World!'
How would I go about? 我该怎么办?
In order to do this try square bracket notation : 为此,请尝试使用方括号表示法 :
function createSimpleObject(name, value){
var obj = {};
obj[name] = value;
return obj;
}
You can't use a variable as a property name in an object literal. 您不能将变量用作对象文字中的属性名称。 You have to create the object, and then assign the value using square bracket notation.
您必须创建对象,然后使用方括号表示法分配值。
var object = {};
object[name] = value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.