通过spread方法将数组元素放入另一个数组中(但略有不同)



我使用了另一种(我的(方法将某个数组的元素存储在另一个数组中,作为spread方法。我使用了join方法,但数组只包含一个。这是我的代码:

const arr = [1, 2, 3];
const newArray = [eval(arr.join(', ')), 4, 5]
console.log(newArray) // [3, 4, 5]

试试这个:

const arr = [1, 2, 3];
const newArray = [...arr, 4, 5];
console.log(newArray);

您可以使用concat

concat()方法将连接两个(或多个(数组,并且不会更改现有数组,而是返回一个新数组,其中包含已连接数组的值。

const arr = [1, 2, 3];
const newArray = arr.concat([4, 5]);
console.log(newArray)

另一种选择是使用排列语法(…((在ES6中介绍(

const arr = [1, 2, 3];
const newArray = [...arr, ...[4, 5]];
console.log(newArray)