展开运算符 vs array.concat() [英] spread operator vs array.concat()

查看:43
本文介绍了展开运算符 vs array.concat()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展运算符array.concat()

let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log([...numbers, ...parts]);

Array.concat() 函数

let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log(numbers.concat(parts));

两个结果是一样的.那么,我们想在什么样的场景中使用它们呢?哪一种最适合性能?

Both results are same. So, what kind of scenarios we want to use them? And which one is best for performance?

推荐答案

好吧 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆