我有一个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这样的速记可用,这样我就不必遍历每个单独的数据数组,逐个添加项?


当前回答

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

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);
}

其他回答

试试这个:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayB.reduce((pre, cur) => [...pre, ...cur], arrayA);
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);
}

使用concat函数,如下所示:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

newArray的值将是[1,2,3,4](arrayA和arrayB保持不变;Concat为结果创建并返回一个新数组)。

在IE中使用concat函数代替push()函数。的例子,

var a=a.concat(a,new Array('amin'));

以下对我来说似乎是最简单的:

var newArray = dataArray1.slice();
newArray.push.apply(newArray, dataArray2);

由于“push”的参数数量是可变的,所以可以使用push函数的apply方法来推送另一个数组的所有元素。它的结构 调用push,使用它的第一个参数(这里是"newArray")作为"this"和 数组的元素作为剩余的参数。

第一个语句中的切片获得第一个数组的副本,因此不需要修改它。

如果你正在使用一个可用slice的javascript版本,你可以将push表达式简化为:

newArray.push(...dataArray2)