我有一个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)
下面的函数没有数组长度的问题,并且比所有建议的解决方案执行得更好:
function pushArray(list, other) {
var len = other.length;
var start = list.length;
list.length = start + len;
for (var i = 0; i < len; i++ , start++) {
list[start] = other[i];
}
}
不幸的是,jspref拒绝接受我的提交,所以这里是使用benchmark.js的结果
Name | ops/sec | ± % | runs sampled
for loop and push | 177506 | 0.92 | 63
Push Apply | 234280 | 0.77 | 66
spread operator | 259725 | 0.40 | 67
set length and for loop | 284223 | 0.41 | 66
在哪里
For循环和push是:
for (var i = 0, l = source.length; i < l; i++) {
target.push(source[i]);
}
推动应用:
target.push.apply(target, source);
接线员:传播
target.push(...source);
最后,“set length And for loop”是上面的函数
如果你的数组不是很大(见下面的警告),你可以使用你想要添加值的数组的push()方法。Push()可以接受多个参数,因此可以使用它的apply()方法将要推送的值数组作为函数参数列表传递。这比使用concat()在数组中添加元素而不是创建新数组更有优势。
然而,对于大型数组(100,000成员的数量级或更多),这种技巧可能会失败。对于这样的数组,使用循环是更好的方法。详情见https://stackoverflow.com/a/17368101/96100。
var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);
你可能想把它泛化成一个函数:
function pushArray(arr, arr2) {
arr.push.apply(arr, arr2);
}
... 或者将其添加到Array的原型:
Array.prototype.pushArray = function(arr) {
this.push.apply(this, arr);
};
var newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);
... 或者模拟原始的push()方法,使用concat(),像push()一样,允许多个参数:
Array.prototype.pushArray = function() {
this.push.apply(this, this.concat.apply([], arguments));
};
var newArray = [];
newArray.pushArray(dataArray1, dataArray2);
下面是上一个例子的循环版本,适用于大型数组和所有主流浏览器,包括IE <= 8:
Array.prototype.pushArray = function() {
var toPush = this.concat.apply([], arguments);
for (var i = 0, len = toPush.length; i < len; ++i) {
this.push(toPush[i]);
}
};
使用JavaScript ES6,你可以使用…运算符作为展开运算符,它本质上将数组转换为值。然后,你可以这样做:
const myArray = [1,2,3,4,5];
const moreData = [6,7,8,9,10];
const newArray = [
...myArray,
...moreData,
];
虽然语法很简洁,但我不知道它在内部是如何工作的,以及对大型数组的性能影响是什么。