4.1 函數參數
在 JavaScript 中,函數參數允許你將值傳遞給函數進行處理。這讓函數更加靈活和適應。在這個主題中,我們會探討在 JavaScript 中使用函數參數的基本方面, 不包括預設參數和剩餘參數。
參數寫在函數名稱後的圓括號中。在調用函數時,這些參數的值會被傳遞給函數內對應的變數。
範例:
函數 greet() 定義了兩個參數:name 和 age。在調用函數時, 值 Alice 和 30 被傳遞給這些參數。
function greet(name, age) {
return `Hello, ${name}! You are ${age} years old.`;
}
console.log(greet('Alice', 30)); // "Hello, Alice! You are 30 years old."
處理未定義的參數
如果在調用函數時未傳遞參數,其值將為 undefined。這可能會導致錯誤,如果對這類參數進行不支持 undefined 的操作時。
範例:
在函數 greet() 中,檢查是否傳遞了參數 name。如果沒有,則使用字串 Guest。
function greet(name) {
if (name === undefined) {
return 'Hello, Guest!';
}
return `Hello, ${name}!`;
}
console.log(greet()); // "Hello, Guest!"
console.log(greet('Bob')); // "Hello, Bob!"
4.2 預設參數
預設參數 允許設置一個值,這個值會在函數調用時未傳遞參數或者傳遞了 undefined 時使用。這對於創建具有可選參數的函數特別有用。
語法:
function name (arg1 = value1, arg2 = value2) {
// function body
}
範例 1:簡單函數的預設參數
在這個範例中,函數 greet() 具有參數 name,預設值為 Guest。如果未傳遞參數,則使用預設值。
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
console.log(greet('Alice')); // 出現: Hello, Alice!
console.log(greet()); // 出現: Hello, Guest!
範例 2:帶有表達式的預設參數
在這個範例中,預設參數 tax 在未傳遞其他參數時計算為 price 的 20%。
function calculatePrice(price, tax = price * 0.2) {
return price + tax;
}
console.log(calculatePrice(100)); // 出現: 120
console.log(calculatePrice(100, 15)); // 出現: 115
範例 3:預設參數依賴其他參數
在這個範例中,預設參數允許創建用戶並設定預設角色和狀態。
function createUser(name, role = 'user', isActive = true) {
return { name, role, isActive };
}
console.log(createUser('Alice')); // 出現: { name: 'Alice', role: 'user', isActive: true }
console.log(createUser('Bob', 'admin')); // 出現: { name: 'Bob', role: 'admin', isActive: true }
console.log(createUser('Charlie', 'moderator', false)); // 出現: { name: 'Charlie', role: 'moderator', isActive: false }
4.3 剩餘參數
剩餘參數 允許函數接收任意數量的參數,並將它們收集到一個數組中。這對於創建可以處理任意數量參數的函數非常有用。
語法:
function name (arg1, arg2, ...argArray) {
// function body
}
範例 1:總和所有傳遞的參數
在這個範例中,函數 sumAll() 使用剩餘參數來總和所有傳遞的參數。
function sumAll(...numbers) {
return numbers.reduce((sum, num) => sum + num, 0);
}
console.log(sumAll(1, 2, 3)); // 出現: 6
console.log(sumAll(4, 5, 6, 7, 8)); // 出現: 30
範例 2:帶有固定及剩餘參數的函數
在這個範例中,函數 showItems() 接收固定參數 firstItem 和不定數量的其它參數,並將它們收集到數組 otherItems 中。
function showItems(firstItem, ...otherItems) {
console.log(`第一個元素: ${firstItem}`);
console.log(`其他元素: ${otherItems.join(', ')}`);
}
showItems('apple', 'banana', 'cherry', 'date');
// 出現:
// 第一個元素: apple
// 其他元素: banana, cherry, date
範例 3:帶有動態參數的函數
在這個範例中,函數 createMessage() 接收第一個參數 messageType,並將所有其他參數收集到數組 messages 中,以創建一條消息。
function createMessage(messageType, ...messages) {
return `[${messageType.toUpperCase()}]: ${messages.join(' ')}`;
}
console.log(createMessage('info', 'This', 'is', 'an', 'informational', 'message'));
// 出現: [INFO]: This is an informational message
console.log(createMessage('error', 'An', 'error', 'occurred'));
// 出現: [ERROR]: An error occurred
GO TO FULL VERSION