是否可以将变量的值用作对象声明中的对象键?

时间:2011-12-07 01:59:21

标签: javascript

我想沿着这些方向做点什么:

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";

2 个答案:

答案 0 :(得分:4)

不,不是直接在对象文字声明中。

无法判断您是否打算将变量值或标识符本身作为属性名称。


如果需要,您可以创建一个辅助函数来获取键/值对的数组:

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"}

答案 1 :(得分:2)

没有。对象文字不能将变量值用作键。你可以引用键的事实可能会让它看起来像真正的价值观,但它们没有。