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 |
浏览器兼容性
加载中…