克服JS奇怪的部分_ arguments與 spread

Huang Pei
Sep 18, 2019

--

參數 (arguments)/ 其餘參數 (rest arguments)/ 展開運算子(spread)

本筆記出自:JavaScript 全攻略:克服 JS 的奇怪部分

參數 (Arguments)

The parameters you pass to a function

JS gives you a keyword of the same name which contains them all

傳入函數的變數的另一個稱呼而已,可以稱呼它為parameters,也可以稱它為arguments

參數也會提升 (hoisting),當函數被執行時,它會預先設定好記憶體空間給參數,並設定它們為undefined

function greet(firstname, lastname, language){  console.log(firstname) //undefined
console.log(lastname) //undefined
console.log(language) //undefined }
greet()

傳入參數會由左至右處理

function greet(firstname, lastname, language){console.log(firstname) //Iris
console.log(lastname) //undefined,為接受到傳入的參數
console.log(language) //undefined,同上 }
greet('Iris')

當沒有參數傳入時使用預設參數

function greet(firstname, lastname, language){  language = language || 'en' (undefined轉型成false也就是0)  console.log(firstname)
console.log(lastname)
console.log(language) }
ES6寫法function greet(firstname, lastname, language = 'en'){
console.log(firstname)
console.log(lastname)
console.log(language) }

Arguments

argument物件是一個對應傳入函式之引數的類陣列Array-like)物件。

function greet(firstname, lastname, language){if(arguments.lenth === 0) { //判斷是否存在參數
console.log('Missing parameters!')
return; }
console.log(arguments) // ['Iris', 'Doe' ,'Taiwanese']
console.log(arguments[0]) //
Iris'
console.log(firstname)
console.log(lastname)
console.log(language) }
greet('Iris', 'Doe' ,'Taiwanese')

*將array -like物件轉換為array的方法:

  • Array.prototype.slice.call(arguments)
  • Array.from(arguments)

其餘參數:將許多參數轉為陣列,適合用在不確定會傳入多少參數的情況

function fun1(...theArgs) {console.log(theArgs.length);}fun1(); // 0,沒有傳入參數fun1(5); // 1,傳入一個參數fun1(5, 6, 7); // 3,傳入三個參數

展開運算子

詳細比較整理

--

--

Huang Pei
Huang Pei

Written by Huang Pei

記錄用倉庫,歡迎指正。菜鳥前端,最菜的那種(超能力少女です)。

No responses yet