在JavaScript中,有多种方法可以用来合并两个数组:
1. `concat()` 方法
```javascript
const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];
const merged = arr1.concat(arr2);
console.log(merged); // Outputs: ['a', 'b', 'c', 'd', 'e', 'f']
```
2. 展开操作符 `...`
```javascript
const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];
const merged = [...arr1, ...arr2];
console.log(merged); // Outputs: ['a', 'b', 'c', 'd', 'e', 'f']
```
3. `Array.prototype.push.apply`
```javascript
const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1); // Outputs: ['a', 'b', 'c', 'd', 'e', 'f']
```
注意:这种方式会改变原始数组。
4. `Array.prototype.push()`
```javascript
const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];
arr1.push(...arr2);
console.log(arr1); // Outputs: ['a', 'b', 'c', 'd', 'e', 'f']
```
注意:这种方式也会改变原始数组。
合并两个数组
最新推荐文章于 2024-07-17 20:16:35 发布