我正在function
创建一个对象:
createObject(attr) {
return {
attr: "test"
}
}
我想attr
命名function parameter
。现在我最终得到了这个对象:
{
attr: "test"
}
我该怎么做?
答案 0 :(得分:4)
创建一个新对象并使用括号表示法来设置属性。
function createObject(attr) {
var obj = {};
obj[attr] = "test";
return obj;
}
答案 1 :(得分:2)
我制作了这支笔,向您展示如何构建对象:
http://codepen.io/dieggger/pen/pJXJex
//function receiving the poarameter to construct the object
var createObject = function(attr) {
//custom object with one predefined value.
var myCustomObject = {
anything: "myAnything",
};
//adding property to the object
myCustomObject[attr] = "Test";
//returning the constructed object
return myCustomObject;
}
//invoking function and assigning the returned object to a variable
var objReturned = createObject("name");
//simple alert , to test if it worked
alert(objReturned.name);
答案 2 :(得分:0)
这样吗?
createObject(attrName) {
var obj = {};
obj[attrName] = 'test';
return obj;
}