简体   繁体   English

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

[英]How to assign multiple values to a JavaScript object?

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

With ES2015 you can use Object.assign :在 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"
}

使用 ES6 扩展运算符:

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

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警告:这几乎肯定是个主意!请参阅链接。我仅出于教育目的发布此内容;您几乎应该在生产代码中使用with !):

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

I would use Object Constructors.我会使用对象构造函数。 Would look something like this:看起来像这样:

function someVar (color,fontSize, fontWeight){
    this.color = color,
    this.fontSize = fontSize,
    this.fontWeight = fontWeight
};
var var1 = new someVar("red","12px","45px");
var myvar ={};
myvar['color']='red';
myvar['width'] ='100px';
alert(myvar.color);

or alert(myvar['color']);alert(myvar['color']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM