Javascript Object.assign(...array) 的替代方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38985624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alternative of Object.assign(...array)
提问by Abdennour TOUMI
Assume we have array of objects.
假设我们有对象数组。
Calling Object.assign(...array)
makes an inheritance among those objects where object with index i
override existing properties in object with index i-1
调用Object.assign(...array)
在那些对象之间进行继承,其中具有索引的对象i
覆盖具有索引的对象中的现有属性i-1
For example:
例如:
var array=[{interf:'IPerson',name:'Someone'},{clss:'Person',name:'Ahmed'},{student:true}];
console.log(
Object.assign(...array) // Object.assign(array[0],array[1],array[2])
)
Now, using Babel with the proposed object spread syntax, we can do this statically :
现在,使用 Babel 和建议的对象传播语法,我们可以静态地做到这一点:
{...array[0],...array[1],...array[2]} // spread used for each object not for array
How to do that dynamically?
如何动态地做到这一点?
There is overlap of context of "spread syntax". I mean how to use spread syntax for both:
“传播语法”的上下文有重叠。我的意思是如何对两者使用传播语法:
- For the Array to spread elements.
- For the output literal object
{}
to make inheritance
- 用于 Array 传播元素。
- 对于输出文字对象
{}
进行继承
?
?
I tried {...array}
and it returns {0:<array[0]>,1:<array[1]>,2:<array[2]>}
which is notthe same output as Object.assign(...array)
.
我试着{...array}
和它返回{0:<array[0]>,1:<array[1]>,2:<array[2]>}
它不是作为输出相同Object.assign(...array)
。
回答by Bergi
You are looking for
你正在寻找
var obj = Object.assign({}, ...array)
that creates a new object instead of mutating array[0]
.
创建一个新对象而不是 mutating array[0]
。
回答by Michael Sherris Caley
Seems to me the method you're looking for is .concat()
在我看来你正在寻找的方法是 .concat()
Returns a new array which is a merge of the target and the source.
返回一个新数组,它是目标和源的合并。
回答by Christiyan
I thing the method you are looking for, as mentioned above, is .concat(), which creates a copie of an array or extends it with another one.
我认为你正在寻找的方法,如上所述,是 .concat(),它创建一个数组的副本或用另一个扩展它。
var a1 = [1,2,3], a2 = [];
a2 = a2.concate(a1);
// or ES5 shorten alternative
// var a1 = [1,2,3], a2 = [].concat(a1);
// or better ES6 shorten alternative
// a2 = [...a1];
a2.push(4);
console.log(a1, a2);
// a1 -> [1,2,3], a2 -> [1,2,3,4]