2.1.7 Spread Operator & Rest Operator
在 ES6 中,新增了一個 "..." 的關鍵字,這個關鍵字在不同時間點有不同的效果,有些時候它會被當作展開運算子(spread operator)使用,有些時候則是被當作其餘運算子(rest operator)使用。
其餘運算子(Rest Operator)
其餘運算字會幫助我們把輸入函式中的參數值變成陣列的形式
function sum(…numbers) {
const result = 0
numbers.forEach(function (number) {
result += number
})
return result
}
sum(1) // 1
sum(1, 2, 3, 4, 5) // 15
展開運算子(Spread Operator)
展開運算符是把一個陣列展開成個別的值的速寫語法,它只會在"陣列字面定義"與"函式呼叫"時使用
const params = [ "hello", true, 7 ]
const other = [ 1, 2, ...params ]
console.log(other)
// [ 1, 2, "hello", true, 7 ]
展開運算符可以作陣列的淺拷貝,當然陣列的淺拷貝有很多種方式,這是一種新語法,也是目前最簡單的一種語法:
const arr = [1,2,3]
const arr2 = [...arr]
arr2.push(4) //不會影響到arr
Last updated
Was this helpful?