我想按照这些思路做一些事情:
var firstName = "alan";
var secondName = "antonella";
var statusOfPeople = {
firstName: "excellent",
secondName: "superb"
};
console.log(JSON.stringify(statusOfPeople));
并得到这个输出:
{ "alan": "excellent", "antonella": "superb" }
这可能吗?不这样做?
var statusOfPeople = {};
statusOfPeople[firstName] = "excellent";
statusOfPeople[secondName] = "superb";
最佳答案
不,不是直接在对象字面量声明中。
无法判断您是打算将变量值还是标识符本身作为属性名称。
如果需要,您可以创建一个接受键/值对数组的辅助函数:
function makeObject() {
var obj = {};
for( var i = 0; i < arguments.length; ++i ) {
obj[ arguments[i][0] ] = arguments[i][1];
}
return obj;
}
像这样使用它:
var firstName = "alan";
var secondName = "antonella";
var statusOfPeople = makeObject(
[firstName, "excellent"],
[secondName, "superb"]
);
console.log(JSON.stringify(statusOfPeople));
// {"alan":"excellent","antonella":"superb"}
如果你这样做,你甚至可以减少语法:
function makeObject() {
var obj = {};
for( var i = 0; i < arguments.length; i+=2 ) {
obj[ arguments[i] ] = arguments[i+1];
}
return obj;
}
然后像这样使用它:
var firstName = "alan";
var secondName = "antonella";
var statusOfPeople = makeObject(
firstName, "excellent",
secondName, "superb"
);
console.log(JSON.stringify(statusOfPeople));
// {"alan":"excellent","antonella":"superb"}
关于javascript - 是否可以在对象声明中使用变量的值作为对象键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8409503/