可以将对象文字内的多个属性设置为相同的值吗? [英] Can one set multiple properties inside an object literal to the same value?
本文介绍了可以将对象文字内的多个属性设置为相同的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我可以这样做吗?:
For example, can I do this?:
{
a: b: c: d: 1,
e: 2,
geh: function() { alert("Hi!") }
}
编辑:
我有什么方法可以避免这样做吗?:
Is there some way I can avoid doing this?:
{
a: 1,
b: 1,
c: 1,
d: 1,
e: 2,
geh: function() { alert("Hi!") }
}
推荐答案
你可以在各种属性之间设置一条平等线:
You could set a line of equality between various properties:
var foo = {};
foo.a = foo.b = foo.c = "Hello";
或者您可以创建一个为您进行批量分配的方法:
Or you could just create a method that does the mass-assignment for you:
var foo = {
setValue: function( props, value ) {
while ( props.length ) this[ props.pop() ] = value;
}
}
foo.setValue( [ "a", "b", "c" ] , "Foo" );
这篇关于可以将对象文字内的多个属性设置为相同的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文