关于javascript:将数组元素添加到另一个数组

Add elements of an array to another array

本问题已经有最佳答案,请猛点这里访问。

有两个数组,例如:

1
2
arr1 = ["a","b"];
arr2 = ["c","d"];

我想把第二个元素添加到第一个元素中,在这个操作之后,arr1应该看起来像["a","b","c","d"]。不管arr2发生了什么。

我尝试了经典的方法:arr1.push(arr2),结果是:["a","b", Array(2)]


您可以使用ES6语法使其:

你可以这样做:

1
2
3
4
5
6
const arr1 = ["a","b"];
const arr2 = ["c","d"];

arr1 = [...arr1,...arr2]

console.log(arr1)

Definition about the spread operator :

允许在需要零个或多个参数(用于函数调用)或元素(用于数组文本)的位置扩展可重复项(如数组表达式或字符串),或在需要零个或多个键值对(用于对象文本)的位置扩展对象表达式。(定义来自MDN)

在ES5语法中,您应该使用.concat()函数,但现在在ES6中更容易使用。


使用Array.prototype.concat()

1
2
3
4
var arr1 = ["a","b"];
var arr2 = ["c","d"];
arr1 = arr1.concat(arr2);
console.log(arr1)


使用排列语法:

1
2
3
4
var arr1 = ["a","b"];
var arr2 = ["c","d"];
arr1 = [...arr1,...arr2];
console.log(arr1);

使用array.concat():

1
2
3
4
var arr1 = ["a","b"];
var arr2 = ["c","d"];
arr1 = arr1.concat(arr2);
console.log(arr1);