let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log([...numbers, ...parts]);
Array.concat()
function
let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log(numbers.concat(parts));
let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log([...numbers, ...parts]);
Array.concat()
function
let parts = ['four', 'five'];
let numbers = ['one', 'two', 'three'];
console.log(numbers.concat(parts));
concat
和...
在参数不是数组时非常不同。
当参数不是数组时,concat
会将其作为一个整体添加,而...
会尝试迭代它,并在无法迭代时失败。请考虑以下例子:
a = [1, 2, 3]
x = 'hello';
console.log(a.concat(x)); // [ 1, 2, 3, 'hello' ]
console.log([...a, ...x]); // [ 1, 2, 3, 'h', 'e', 'l', 'l', 'o' ]
在这里,concat
将字符串视为一个整体处理,而 ...
使用它的默认迭代器,逐个字符处理。
另一个例子:
x = 99;
console.log(a.concat(x)); // [1, 2, 3, 99]
console.log([...a, ...x]); // TypeError: x is not iterable
< p > 对于 concat
,数字是一个原子,...
尝试迭代它并失败了。 < /p>
< p > 最后: < /p>function* gen() { yield *'abc' }
console.log(a.concat(gen())); // [ 1, 2, 3, Object [Generator] {} ]
console.log([...a, ...gen()]); // [ 1, 2, 3, 'a', 'b', 'c' ]
concat
不尝试迭代生成器并将其作为整体附加,而 ...
会从中取出所有值。
总之,当你的参数可能不是数组时,选择使用 concat
还是 ...
取决于你是否想要迭代它们。
上述描述了 concat
的默认行为,然而,ES6 提供了一种方式 使用 Symbol.isConcatSpreadable
来覆盖该行为。默认情况下,这个符号对于数组是 true
,对于其他所有内容都是 false
。将其设置为 true
告诉 concat
迭代该参数,就像 ...
所做的那样:
str = 'hello'
console.log([1,2,3].concat(str)) // [1,2,3, 'hello']
str = new String('hello');
str[Symbol.isConcatSpreadable] = true;
console.log([1,2,3].concat(str)) // [ 1, 2, 3, 'h', 'e', 'l', 'l', 'o' ]
在性能方面,concat
更快,可能因为它可以从数组特定的优化中受益,而 ...
必须符合通用的迭代协议。时间:
let big = (new Array(1e5)).fill(99);
let i, x;
console.time('concat-big');
for(i = 0; i < 1e2; i++) x = [].concat(big)
console.timeEnd('concat-big');
console.time('spread-big');
for(i = 0; i < 1e2; i++) x = [...big]
console.timeEnd('spread-big');
let a = (new Array(1e3)).fill(99);
let b = (new Array(1e3)).fill(99);
let c = (new Array(1e3)).fill(99);
let d = (new Array(1e3)).fill(99);
console.time('concat-many');
for(i = 0; i < 1e2; i++) x = [1,2,3].concat(a, b, c, d)
console.timeEnd('concat-many');
console.time('spread-many');
for(i = 0; i < 1e2; i++) x = [1,2,3, ...a, ...b, ...c, ...d]
console.timeEnd('spread-many');
array.concat
方法对我来说无法正常工作。所以我不得不使用array.push(...spread)
方法。我找到了这个链接,它讨论了TypeScript中的concat问题,并建议使用([] as any[]).concat(myArray)
,但似乎也不起作用。 - Gangulaconsole.log(['one', 'two', 'three', 'four', 'five'])
和 concat
的结果相同,那么在这里为什么要使用它们呢? :P
通常情况下,当你有来自任意来源的两个(或多个)数组时,你会使用 concat
,而如果始终包含已知附加元素的数组文字,则会在数组文字中使用扩展语法。因此,如果你的代码中有一个带有 concat
的数组文字,只需使用扩展语法即可,否则就使用 concat
:
[...a, ...b] // bad :-(
a.concat(b) // good :-)
[x, y].concat(a) // bad :-(
[x, y, ...a] // good :-)
此外,当处理非数组值时,这两种替代方案的行为差异很大。
['one',...parts,'two','three'];
。现在 four and five
移动到第二个位置。这在 concat()
中可行吗? - Ramesh Rajendran['one'].concat(parts, ['two', 'three'])
(如果您不想传递多个参数,则为 ['one'].concat(parts).concat(['two', 'three'])
)。 - Bergi.concat(x)
使读者认为 x
也是一个数组。当然,concat
也可以处理非数组值,但在我看来,这不是它的主要操作模式。特别是如果 x
是任意(未知)值,你需要编写 .concat([x])
来确保它始终按预期工作。而且,一旦你必须编写一个数组字面量,我建议你使用扩展语法而不是 concat
。 - Bergi.concat()
更快,否则假设两个参数都是列表,则它们的工作方式相同。下面是合并每个具有 1000 万个元素的两个数组所需的时间(较低的值更好):
浏览器 | [...a, ...b] |
a.concat(b) |
---|---|---|
Chrome 113 | 350ms | 30ms |
Firefox 113 | 400ms | 63ms |
Safari 16.4 | 92ms | 71ms |
我在一台配备 8GB RAM 的 M1 MacBook Air 上运行了此代码:
const arraySize = 10000000;
const trials = 50;
const array1 = [];
const array2 = [];
for (let i = 0; i < arraySize; ++i) {
array1.push(i);
array2.push(i);
}
let spreadTime = 0;
for (let i = 0; i < trials; ++i) {
const start = performance.now();
const array3 = [...array1, ...array2];
const end = performance.now();
spreadTime += end - start;
}
let concatTime = 0;
for (let i = 0; i < trials; ++i) {
const start = performance.now();
const array3 = array1.concat(array2);
const end = performance.now();
concatTime += end - start;
}
// performance.now() returns milliseconds with a
// 5 microsecond resolution in isolated contexts and a
// 100 microsecond resolution in non-isolated contexts.
spreadTime = Math.round(spreadTime / trials * 1000) / 1000;
concatTime = Math.round(concatTime / trials * 1000) / 1000;
console.log(`${arraySize} items - spread: ${spreadTime}ms concat: ${concatTime}ms`);
我认为唯一有效的区别是,当使用展开运算符处理大型数组时,可能会出现错误:Maximum call stack size exceeded
,你可以通过使用concat
运算符来避免这个问题。
var someArray = new Array(600000);
var newArray = [];
var tempArray = [];
someArray.fill("foo");
try {
newArray.push(...someArray);
} catch (e) {
console.log("Using spread operator:", e.message)
}
tempArray = newArray.concat(someArray);
console.log("Using concat function:", tempArray.length)
更新:
concat
现在始终比spread
更快。以下基准测试显示了合并小型和大型数组的性能差异: https://jsbench.me/nyla6xchf4/1
// preparation
const a = Array.from({length: 1000}).map((_, i)=>`${i}`);
const b = Array.from({length: 2000}).map((_, i)=>`${i}`);
const aSmall = ['a', 'b', 'c', 'd'];
const bSmall = ['e', 'f', 'g', 'h', 'i'];
const c = [...a, ...b];
// vs
const c = a.concat(b);
const c = [...aSmall, ...bSmall];
// vs
const c = aSmall.concat(bSmall)
之前:
虽然在大数组上,一些回答是正确的,但在处理小数组时,性能相当不同。
您可以在https://jsperf.com/spread-vs-concat-size-agnostic上自行检查结果。
正如您所看到的,展开操作符对于较小的数组要快50%,而concat
在大数组上快多次。
concat
和push
之间有一个非常重要的区别,即前者不会改变底层数组,需要将结果分配给相同或不同的数组:
let things = ['a', 'b', 'c'];
let moreThings = ['d', 'e'];
things.concat(moreThings);
console.log(things); // [ 'a', 'b', 'c' ]
things.push(...moreThings);
console.log(things); // [ 'a', 'b', 'c', 'd', 'e' ]
我曾经见过由于假设 concat
改变数组而引起的错误(代表我的朋友说的)。
@georg的回答对比较有帮助。我也很好奇.flat()在运行时的表现如何,结果是最差的。如果速度是优先考虑的因素,请勿使用.flat()。(这是我直到现在才意识到的事情)
let big = new Array(1e5).fill(99);
let i, x;
console.time("concat-big");
for (i = 0; i < 1e2; i++) x = [].concat(big);
console.timeEnd("concat-big");
console.time("spread-big");
for (i = 0; i < 1e2; i++) x = [...big];
console.timeEnd("spread-big");
console.time("flat-big");
for (i = 0; i < 1e2; i++) x = [[], big].flat();
console.timeEnd("flat-big");
let a = new Array(1e3).fill(99);
let b = new Array(1e3).fill(99);
let c = new Array(1e3).fill(99);
let d = new Array(1e3).fill(99);
console.time("concat-many");
for (i = 0; i < 1e2; i++) x = [1, 2, 3].concat(a, b, c, d);
console.timeEnd("concat-many");
console.time("spread-many");
for (i = 0; i < 1e2; i++) x = [1, 2, 3, ...a, ...b, ...c, ...d];
console.timeEnd("spread-many");
console.time("flat-many");
for (i = 0; i < 1e2; i++) x = [1, 2, 3, a, b, c, d].flat();
console.timeEnd("flat-many");
let big = (new Array(1e5)).fill(99);
let big2 = (new Array(1e5)).fill(99);
let res = []
console.time('concat-many');
for (i = 0; i < 1e2; i++) res = big.concat(big2)
console.timeEnd('concat-many');
console.time('concat-many-with-reset');
for (i = 0; i < 1e2; i++) big = big.concat(big2)
console.timeEnd('concat-many-with-reset');
res = []
big = (new Array(1e5)).fill(99);
console.time('spread-many');
for (i = 0; i < 1e2; i++) res = [...big, ...big2]
console.timeEnd('spread-many');
console.time('spread-many-with-reset');
for (i = 0; i < 1e2; i++) big = [...big, ...big2]
console.timeEnd('spread-many-with-reset');