1. ホーム
  2. javascript

[解決済み] spread 演算子と array.concat() の比較

2023-01-13 23:52:49

質問

とはどのような違いがあるのでしょうか? spread operatorarray.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));

どちらの結果も同じです。では、どのようなシナリオでそれらを使用したいのでしょうか?また、どちらがパフォーマンス的に最適なのでしょうか?

どのように解決するのか?

さて console.log(['one', 'two', 'three', 'four', 'five']) も同じ結果なので、なぜここでどちらを使うのでしょうか?

一般に、あなたは concat を使用します。また、常に配列の一部である追加要素が事前に分かっている場合は、 配列リテラルでスプレッド構文を使用します。ですから、もし配列リテラルに concat という配列リテラルがある場合、スプレッドシンタックスで concat を使ってください。

[...a, ...b] // bad :-(
a.concat(b) // good :-)

[x, y].concat(a) // bad :-(
[x, y, ...a]    // good :-)

また、配列以外の値を扱う場合、2つの選択肢は全く異なる振る舞いをします。