參數 (arguments)/ 其餘參數 (rest arguments)/ 展開運算子(spread)
參數 (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)