我有一个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);
}
在ECMAScript 6中,你可以使用Spread语法:
设arr1 = [0,1,2];
Let arr2 = [3,4,5];
arr1.push(…arr2);
console.log (arr1)
扩展语法在所有主流浏览器(不包括IE11)中都可用。关于当前的兼容性,请参见这个(不断更新的)兼容性表。
但是,请参阅下面杰克·吉芬的回复,了解更多关于性能的评论。似乎concat仍然比spread算子更好更快。