How to assign multiple values to a JavaScript object?

一个人想着一个人 提交于 2019-11-28 08:55:03

问题


Say that I have an object with key/value pair as the following:

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

Is there a way to do a multiple assignment to those keys instead of having to do something like this:

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

回答1:


You could loop through another object:

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

Or, you could use with (WARNING: this is ALMOST CERTAINLY a bad idea! See the link. I am only posting this for educational purposes; you should almost never use with in production code!):

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



回答2:


With ES2015 you can use 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"
}



回答3:


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

or alert(myvar['color']);



来源:https://stackoverflow.com/questions/22109929/how-to-assign-multiple-values-to-a-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!