我尝试了此操作,但是它只将值设置为obj1
let obj1, obj2, obj3, obj4, ..., objn = {} // only obj1 is set, the rest is undefined.
我看了这篇文章:assign multiple variables to the same value in Javascript,他们提出了这个建议:
let obj1 = obj2 = obj3 = obj4 = ... = objn = {}
但是上面说obj1
中的任何更改都会影响obj2
,obj3
,...
是否可以在没有for循环的情况下立即将所有obj
初始化为{}
?
答案 0 :(得分:1)
使用数组解构分配,您可以使用map / reduce创建对象,但它们都不会像for-like循环那样快。
let [o1,o2,o3] = Array(3).fill().map(()=>({}))
o1.id = '1'
o2.id = '2'
o3.id = '3'
console.log(o1)
console.log(o2)
console.log(o3)
答案 1 :(得分:0)
您可以使用Object.assign
,此函数带有ES6语法,您可以查看文档:{{3}}
const [obj1, obj2, obj3] = [{id: 1}, {id: 2}, {id: 3}];
Object.assign(this, {obj1, obj2, obj3});
答案 2 :(得分:0)
var [obj, obj2, obj3] = [{"a":1},{"a":2},{"a":3}];
console.log(obj);
console.log(obj2);
console.log(obj3);
这似乎可行。
答案 3 :(得分:0)
let {obj1, obj2, obj3 }= {obj1:{}, obj2:{}, obj3:{}};
obj1.id =10;
obj2.id =20;
obj3.id =30;
console.log("obj1",obj1);
console.log("obj2",obj2);
console.log("obj3",obj3);
答案 4 :(得分:0)
这是一种初始化任意数量的对象而无需显式初始化值数组的有趣方法。这个答案与Vol7ron's answer非常相似,除了它使用generator function来延迟迭代值而无需预先分配数组。由 implementation "com.android.support:recyclerview-v7:$supportLibVersion"
implementation "com.android.support:preference-v7:$supportLibVersion"
implementation "com.android.support:animated-vector-drawable:$supportLibVersion"
implementation "com.android.support:customtabs:$supportLibVersion"
implementation "com.android.support:design:$supportLibVersion"
implementation "com.android.support:appcompat-v7:$supportLibVersion"
implementation "com.android.support:cardview-v7:$supportLibVersion"
implementation "com.android.support:support-v4:$supportLibVersion"
implementation "com.android.support:support-vector-drawable:$supportLibVersion"
ext {
supportLibVersion = '27.1.1'
}
返回的迭代器只会按照destructuring assignment的要求进行迭代,因此请确保不要在解构分配中使用...
rest parameter,否则迭代器将永远不会终止。
initialize()
答案 5 :(得分:0)
function declareMultipleObjects(...args){
var arrayOfObjects = []
args.forEach(function(each){
each = new Object();
arrayOfObjects.push(each);
})
alert(arrayOfObjects);}
declareMultipleObjects("obj1", "obj2", "obj3");