如何为JavaScript对象分配多个值? [英] How to assign multiple values to a JavaScript object?
本文介绍了如何为JavaScript对象分配多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个带键/值对的对象如下:
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";
...
推荐答案
你可以循环另一个对象:
You could loop through another object:
var thingsToAdd = {
color: "blue",
font_size: "30px"
};
for (var x in thingsToAdd) someVar[x] = thingsToAdd[x];
或者,您可以使用 with
( 警告 :这几乎只是一个糟糕的想法!请参阅链接。我只是出于教育目的发布此内容;您几乎从不使用在生产代码中使用
!):
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";
}
这篇关于如何为JavaScript对象分配多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文