本章學習要點: 1、擴展運算符 含義:擴展運算符(spread)是三個點(...)。它好比 rest 參數的逆運算,將一個數組轉為用逗號分隔的參數序列。 該運算符主要用於函數調用。 上面代碼中add(...numbers)是函數的調用,它使用了擴展運算符。該運算符將一個數組,變為參數序列。 擴展運算 ...
本章學習要點:
- 擴展運算符
- Array.from()
- Array.of()
- 數組實例的 copyWithin()
- 數組實例的 find() 和 findIndex()
- 數組實例的 fill()
- 數組實例的 entries(),keys() 和 values()
- 數組實例的 includes()
- 數組實例的 flat(),flatMap()
- 數組的空位
1、擴展運算符
含義:擴展運算符(spread)是三個點(...
)。它好比 rest 參數的逆運算,將一個數組轉為用逗號分隔的參數序列。
console.log(...[1, 2, 3]) // 1 2 3 console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5 [...document.querySelectorAll('div')] // [<div>, <div>, <div>]
該運算符主要用於函數調用。
function add(x, y) { return x + y; } const numbers = [4, 38]; add(...numbers) // 42
上面代碼中add(...numbers)
是函數的調用,它使用了擴展運算符。該運算符將一個數組,變為參數序列。
擴展運算符後面還可以放置表達式。
let x = 0; const arr = [ ...(x > 0 ? ['a'] : []), 'b', ]; console.log(arr) // ["b"]
如果擴展運算符後面是一個空數組,則不產生任何效果。
[...[], 1] // [1]
註意,擴展運算符如果放在括弧中,JavaScript 引擎就會認為這是函數調用。如果這時不是函數調用,就會報錯。
(...[1, 2]) // Uncaught SyntaxError: Unexpected number console.log((...[1, 2])) // Uncaught SyntaxError: Unexpected number console.log(...[1, 2]) // 1 2