问题描述
spread operator
和array.concat()
let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log([...numbers, ...parts]);
Array.concat()函数
Array.concat() function
let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log(numbers.concat(parts));
推荐答案
console.log(['one', 'two', 'three', 'four', 'five'])
也具有相同的结果,那么为什么在此处使用两者之一? :P
Well console.log(['one', 'two', 'three', 'four', 'five'])
has the same result as well, so why use either here? :P
通常,当您有两个(或多个)来自任意源的数组时,将使用concat
,并且如果以前知道始终是数组一部分的其他元素,则可以在数组文字中使用扩展语法.因此,如果您的代码中包含带concat
的数组文字,则只需使用扩展语法即可,否则请使用concat
In general you would use concat
when you have two (or more) arrays from arbitrary sources, and you would use the spread syntax in the array literal if the additional elements that are always part of the array are known before. So if you would have an array literal with concat
in your code, just go for spread syntax, and just use concat
otherwise:
[...a, ...b] // bad :-(
a.concat(b) // good :-)
[x, y].concat(a) // bad :-(
[x, y, ...a] // good :-)
在处理非数组值时,这两种选择的行为也大不相同.
Also the two alternatives behave quite differently when dealing with non-array values.
这篇关于传播算子vs array.concat()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!