Array.prototype.concat()
Array 例項的 concat() 方法用於合併一個或多個數組。此方法不會更改現有陣列,而是返回一個新陣列。
試一試
const array1 = ["a", "b", "c"];
const array2 = ["d", "e", "f"];
const array3 = array1.concat(array2);
console.log(array3);
// Expected output: Array ["a", "b", "c", "d", "e", "f"]
語法
concat()
concat(value1)
concat(value1, value2)
concat(value1, value2, /* …, */ valueN)
引數
value1, …,valueN可選-
要合併到新陣列中的陣列和/或值。如果省略了所有
valueN引數,concat將返回呼叫它的現有陣列的淺複製。有關更多詳細資訊,請參閱下面的說明。
返回值
一個新的 Array 例項。
描述
concat 方法建立一個新陣列。陣列將首先由其呼叫的物件中的元素填充。然後,對於每個引數,其值將被合併到陣列中 — 對於普通物件或原始值,該引數本身將成為最終陣列的一個元素;對於具有設定為真值的 Symbol.isConcatSpreadable 屬性的陣列或類陣列物件,該引數的每個元素都將獨立新增到最終陣列中。concat 方法不會遞迴處理巢狀的陣列引數。
concat() 方法是一個複製方法。它不會更改 this 或作為引數提供的任何陣列,而是返回一個淺複製,其中包含與原始陣列相同的元素。
如果源陣列中存在空槽(即稀疏陣列),concat() 方法會保留這些空槽。
concat() 方法是泛型的。this 值與其他引數的處理方式相同(除了它首先會被轉換為物件),這意味著普通物件將直接新增到結果陣列的前面,而具有真值 [Symbol.isConcatSpreadable] 的類陣列物件將被展開到結果陣列中。
示例
合併兩個陣列
以下程式碼合併了兩個陣列
const letters = ["a", "b", "c"];
const numbers = [1, 2, 3];
const alphaNumeric = letters.concat(numbers);
console.log(alphaNumeric);
// results in ['a', 'b', 'c', 1, 2, 3]
合併三個陣列
以下程式碼合併了三個陣列
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
const numbers = num1.concat(num2, num3);
console.log(numbers);
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
將值合併到陣列中
以下程式碼將三個值合併到一個數組中
const letters = ["a", "b", "c"];
const alphaNumeric = letters.concat(1, [2, 3]);
console.log(alphaNumeric);
// results in ['a', 'b', 'c', 1, 2, 3]
合併巢狀陣列
以下程式碼合併了巢狀陣列並演示了引用的保留
const num1 = [[1]];
const num2 = [2, [3]];
const numbers = num1.concat(num2);
console.log(numbers);
// results in [[1], 2, [3]]
// modify the first element of num1
num1[0].push(4);
console.log(numbers);
// results in [[1, 4], 2, [3]]
合併具有 Symbol.isConcatSpreadable 的類陣列物件
concat 預設情況下不會將所有類陣列物件都視為陣列 — 僅當 Symbol.isConcatSpreadable 設定為真值(例如 true)時才會。
const obj1 = { 0: 1, 1: 2, 2: 3, length: 3 };
const obj2 = { 0: 1, 1: 2, 2: 3, length: 3, [Symbol.isConcatSpreadable]: true };
console.log([0].concat(obj1, obj2));
// [ 0, { '0': 1, '1': 2, '2': 3, length: 3 }, 1, 2, 3 ]
在稀疏陣列上使用 concat()
如果任何源陣列是稀疏的,結果陣列也將是稀疏的
console.log([1, , 3].concat([4, 5])); // [1, empty, 3, 4, 5]
console.log([1, 2].concat([3, , 5])); // [1, 2, 3, empty, 5]
在非陣列物件上呼叫 concat()
如果 this 值不是陣列,它將被轉換為物件,然後按照 concat() 的引數的相同方式進行處理。在這種情況下,返回值始終是一個普通的、新的陣列。
console.log(Array.prototype.concat.call({}, 1, 2, 3)); // [{}, 1, 2, 3]
console.log(Array.prototype.concat.call(1, 2, 3)); // [ [Number: 1], 2, 3 ]
const arrayLike = {
[Symbol.isConcatSpreadable]: true,
length: 2,
0: 1,
1: 2,
2: 99, // ignored by concat() since length is 2
};
console.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4]
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-array.prototype.concat |
瀏覽器相容性
載入中…