我有一个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);
}
关于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]
使用JavaScript ES6,你可以使用…运算符作为展开运算符,它本质上将数组转换为值。然后,你可以这样做:
const myArray = [1,2,3,4,5];
const moreData = [6,7,8,9,10];
const newArray = [
...myArray,
...moreData,
];
虽然语法很简洁,但我不知道它在内部是如何工作的,以及对大型数组的性能影响是什么。