我有一个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 newArray = dataArray1.slice();
newArray.push.apply(newArray, dataArray2);
由于“push”的参数数量是可变的,所以可以使用push函数的apply方法来推送另一个数组的所有元素。它的结构
调用push,使用它的第一个参数(这里是"newArray")作为"this"和
数组的元素作为剩余的参数。
第一个语句中的切片获得第一个数组的副本,因此不需要修改它。
如果你正在使用一个可用slice的javascript版本,你可以将push表达式简化为:
newArray.push(...dataArray2)
下面的函数没有数组长度的问题,并且比所有建议的解决方案执行得更好:
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”是上面的函数
我们有两个数组a和b,这里的代码是将数组a的值推入数组b。
let a = [2, 4, 6, 8, 9, 15]
function transform(a) {
let b = ['4', '16', '64']
a.forEach(function(e) {
b.push(e.toString());
});
return b;
}
transform(a)
[ '4', '16', '64', '2', '4', '6', '8', '9', '15' ]
从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"]