我们在js中,如果将一个数组添加进另一个数组中,有什么办法呢?
第1种是for循环
let totalNums = [ ]
const nums1 = [6, 8, 9];
const nums = [20, 40, 60];
for(let n of nums1) {
totalNums.push(n)
}
第2种是使用push(…nums1),这种是属性解构(解析),它会将nums1数组中所有的元素依次解析出来,然后依次加到totalNums里面进去,加…(3个点)的意思是将nums1数组解析出来成6,8,9。
totalNums.push(...nums1)
再啰嗦一下~
我们不能直接
totalNums.push([6, 8, 9])
这个样的话,结果就成了totalNums[[6, 8, 9]]
而是要成下方这种形式,即通过...解构后,
totalNums.push(...nums1)
就是这种形式
totalNums.push(6, 8, 9)
这样结果就是正确的totalNums[6, 8, 9]形式
这个其实是利用了push()函数可以同时载入多个值的特性,我们看一下es5中这个push()函数是怎么样的?
/**
* Removes the last element from an array and returns it.
*/
pop(): T | undefined;
/**
* Appends new elements to an array, and returns the new length of the array.
* @param items New elements of the Array.
*/
push(...items: T[]): number;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: ConcatArray<T>[]): T[];
这个push()函数的源码注释是:追加新的元素(一个或多个)到数组,并且返回数组的长度