我有一个JavaScript数组dataArray,我想把它推到一个新数组newArray。只是我不想让newArray[0]为dataArray。我想把所有的项都推入新数组:

var newArray = [];

newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...

或者更好:

var newArray = new Array (
   dataArray1.values(),
   dataArray2.values(),
   // ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself
);

现在新数组包含了各个数据数组的所有值。是否有一些像pushValues这样的速记可用,这样我就不必遍历每个单独的数据数组,逐个添加项?


当前回答

这是ES6的方式

var newArray = []; 数据1 = [1,2,3,4] 请注意数据2 = [5,6,7,8] 纽瓦雷= [..]dataArray1, ... dataArray2] console . log (newArray)

上面的方法适用于大多数情况,在不适用的情况下请考虑concat,比如数组中有数十万项。

数据1 = [1,2,3,4] 请注意数据2 = [5,6,7,8] 让纽瓦雷= dataArray1.concat(dataArray2); console . log (newArray)

其他回答

如果你想修改原始数组,你可以展开和推:

var source = [1, 2, 3];
var range = [5, 6, 7];
var length = source.push(...range);

console.log(source); // [ 1, 2, 3, 5, 6, 7 ]
console.log(length); // 6

如果你想确保源数组中只有相同类型的项(例如,不要混合数字和字符串),那么使用TypeScript。

/**
 * Adds the items of the specified range array to the end of the source array.
 * Use this function to make sure only items of the same type go in the source array.
 */
function addRange<T>(source: T[], range: T[]) {
    source.push(...range);
}

这是ES6的方式

var newArray = []; 数据1 = [1,2,3,4] 请注意数据2 = [5,6,7,8] 纽瓦雷= [..]dataArray1, ... dataArray2] console . log (newArray)

上面的方法适用于大多数情况,在不适用的情况下请考虑concat,比如数组中有数十万项。

数据1 = [1,2,3,4] 请注意数据2 = [5,6,7,8] 让纽瓦雷= dataArray1.concat(dataArray2); console . log (newArray)

从MDN找到了一个优雅的方式

var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];

// Merge the second array into the first one
// Equivalent to vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

或者你可以使用ES6的扩展操作符特性:

let fruits = [ 'apple', 'banana'];
const moreFruits = [ 'orange', 'plum' ];

fruits.push(...moreFruits); // ["apple", "banana", "orange", "plum"]

使用JavaScript ES6,你可以使用…运算符作为展开运算符,它本质上将数组转换为值。然后,你可以这样做:

const myArray = [1,2,3,4,5];
const moreData = [6,7,8,9,10];

const newArray = [
  ...myArray,
  ...moreData,
];

虽然语法很简洁,但我不知道它在内部是如何工作的,以及对大型数组的性能影响是什么。

试试这个:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayB.reduce((pre, cur) => [...pre, ...cur], arrayA);
console.log(newArray)