我有一个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这样的速记可用,这样我就不必遍历每个单独的数据数组,逐个添加项?
下面的函数没有数组长度的问题,并且比所有建议的解决方案执行得更好:
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”是上面的函数
如果你想修改原始数组,你可以展开和推:
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);
}
下面的函数没有数组长度的问题,并且比所有建议的解决方案执行得更好:
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”是上面的函数