我有一个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这样的速记可用,这样我就不必遍历每个单独的数据数组,逐个添加项?
关于array。prototype。push。apply有很多答案。这里有一个明显的例子:
数据1 = [1,2];
变量dataArray2 = [3,4,5];
var newArray = [];
阵列原型推送。apply (newArray, dataArray1);// newArray = [1,2]
阵列原型推送。apply (newArray, dataArray2);// newArray = [1,2,3,4,5]
console . log (JSON stringify (newArray));//输出:[1、2、3、4、5]
如果你有ES6语法:
数据1 = [1,2];
变量dataArray2 = [3,4,5];
var newArray = [];
newArray。push (... dataArray1);// newArray = [1,2]
newArray。push (... dataArray2);// newArray = [1,2,3,4,5]
console . log (JSON stringify (newArray));//输出:[1、2、3、4、5]
从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"]
下面的函数没有数组长度的问题,并且比所有建议的解决方案执行得更好:
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”是上面的函数