JavaScript 如何合并数组

1. concat()方法:

使用concat()方法将两个或多个数组合并为一个新数组。

示例代码

const array1 = [1, 2, 3];

const array2 = [4, 5, 6];

const mergedArray = array1.concat(array2);

console.log(mergedArray); // 输出 [1, 2, 3, 4, 5, 6]

2. Spread Operator(展开运算符):

使用展开运算符将两个或多个数组合并为一个新数组。

示例代码:

const array1 = [1, 2, 3];

const array2 = [4, 5, 6];

const mergedArray = [...array1, ...array2];

console.log(mergedArray); // 输出 [1, 2, 3, 4, 5, 6]

3. push()方法:

使用push()方法将一个数组的元素添加到另一个数组的末尾。

示例代码:

const array1 = [1, 2, 3];

const array2 = [4, 5, 6];

array2.push(...array1);

console.log(array2); // 输出 [4, 5, 6, 1, 2, 3]

4. unshift()方法:

使用unshift()方法将一个数组的元素添加到另一个数组的开头。

示例代码:

const array1 = [1, 2, 3];

const array2 = [4, 5, 6];

array2.unshift(...array1);

console.log(array2); // 输出 [1, 2, 3, 4, 5, 6]

5. splice()方法:

使用splice()方法将一个数组的元素插入到另一个数组的指定位置。

示例代码:

const array1 = [1, 2, 3];

const array2 = [4, 5, 6];

array2.splice(1, 0, ...array1);

console.log(array2); // 输出 [4, 1, 2, 3, 5, 6]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值