如何为JavaScript对象分配多个值?

时间:2014-03-01 04:01:52

标签: javascript object key-value

假设我有一个带键/值对的对象如下:

var someVar = {
    color: "white",
    font_size: "30px",
    font_weight: "normal"
...some more variables and functions
};

有没有办法对这些键进行多重分配,而不必执行以下操作:

someVar.color = "blue";
someVar.font_size = "30px";
...

5 个答案:

答案 0 :(得分:4)

使用ES2015,您可以使用Object.assign

const someVar = {
    color: "white",
    font_size: "30px",
    font_weight: "normal"
};

const newVar = Object.assign({}, someVar, { 
    color: "blue", 
    font_size: "30px"});

console.log(newVar);

=>

{
    color: "blue",
    font_size: "30px",
    font_weight: "normal"
}

答案 1 :(得分:2)

你可以遍历另一个对象:

var thingsToAdd = {
    color: "blue",
    font_size: "30px"
};
for (var x in thingsToAdd) someVar[x] = thingsToAdd[x];

或者,你可以使用with 警告 :这几乎只是糟糕的想法!请参阅链接。我我只发布这个用于教育目的;你几乎从不在生产代码中使用with!):

with (someVar) {
    color = "blue";
    font_size = "30px";
}

答案 2 :(得分:0)

使用ES6 Spread运算符:

someVar = {...someVar, color: "blue", font_size: "30px"}

答案 3 :(得分:0)

我会使用对象构造函数。 看起来像这样:

function someVar (color,fontSize, fontWeight){
    this.color = color,
    this.fontSize = fontSize,
    this.fontWeight = fontWeight
};
var var1 = new someVar("red","12px","45px");

答案 4 :(得分:-2)

var myvar ={};
myvar['color']='red';
myvar['width'] ='100px';
alert(myvar.color);

alert(myvar['color']);