JavaScript concat 方法
最后修改于 2025 年 4 月 4 日
在本文中,我们展示了如何使用 JavaScript 中的 concat 方法合并数组。
数组连接
数组连接是将两个或多个数组首尾相连的操作。 concat 方法用于合并两个或多个数组,而不会修改原始数组。相反,它返回一个包含已连接元素的新数组。
当您需要组合来自多个来源的数据,同时保留原始数组时,此方法非常有用。 concat 方法不会更改现有数组,但会返回一个新数组。
concat 方法可以接受多个数组参数或非数组值。当传递非数组值时,它们作为单个元素添加到新数组中。原始数组在连接操作后保持不变。
基本的 concat 示例
以下示例演示了 concat 方法的基本用法。
main.js
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const arr3 = arr1.concat(arr2); console.log(arr1); // Original array unchanged console.log(arr2); // Original array unchanged console.log(arr3); // New concatenated array
我们创建两个数组并将它们连接起来。原始数组保持未修改状态。 concat() 方法返回一个包含两个数组中所有元素的新数组。
$ node main.js [ 1, 2, 3 ] [ 4, 5, 6 ] [ 1, 2, 3, 4, 5, 6 ]
连接多个数组
concat 方法可以接受多个数组参数。
main.js
const letters = ['a', 'b']; const numbers = [1, 2]; const symbols = ['!', '@']; const combined = letters.concat(numbers, symbols); console.log(combined);
我们将三个数组连接成一个新数组。 concat 方法接受多个数组参数,用逗号分隔。元素按照数组指定的顺序添加。
$ node main.js [ 'a', 'b', 1, 2, '!', '@' ]
连接数组和值
concat() 方法也可以将非数组值作为参数。
main.js
const colors = ['red', 'green'];
const newColors = colors.concat('blue', ['yellow', 'purple']);
console.log(newColors);
我们将一个数组与一个字符串和另一个数组连接起来。字符串作为单个元素添加。嵌套数组的元素被单独添加,而不是作为嵌套数组添加。
$ node main.js [ 'red', 'green', 'blue', 'yellow', 'purple' ]
连接嵌套数组
concat 方法不会递归地展平嵌套数组。
main.js
const arr1 = [1, 2, [3, 4]]; const arr2 = [[5, 6], 7, 8]; const combined = arr1.concat(arr2); console.log(combined);
连接包含嵌套数组的数组时,嵌套数组在结果数组中保留为单个元素。 concat() 方法不会展平嵌套结构。
$ node main.js [ 1, 2, [ 3, 4 ], [ 5, 6 ], 7, 8 ]
使用 concat 复制数组
concat 方法可用于创建数组的浅拷贝。
main.js
const original = [1, 2, 3]; const copy = original.concat(); console.log(original); console.log(copy); console.log(original === copy); // false - different references
调用不带参数的 concat 将创建一个包含相同元素的新数组。这将创建一个浅拷贝,其中复制基本值,但对象引用在数组之间共享。
$ node main.js [ 1, 2, 3 ] [ 1, 2, 3 ] false
来源
在本文中,我们演示了如何使用 concat() 方法在 JavaScript 中合并数组。
作者
列出 所有 JS 数组函数。