spread和rest運算符都是...
+變量/參數的形式
spread
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
console.log([1, ...[2, 3, 4], 5])
//[1,2,3,4,5]
function add(x, y) {
return x + y;
}
const numbers = [4, 38];
add(...numbers) // 42
spread主要是...[Array]
對數組的展開
rest
function push(...items) {
console.log(items);
}
let a = 4;
push(a, 1, 2, 3)
//[4,1,2,3]
rest主要是在函數的參數位置對於多個參數的轉化成數組形式。而且只能把rest參數放在函數的最後一個位置。如果(array,...items,other)
會報錯