问题
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