arguments
對象是 JavaScript 中的一個特殊對象,它包含了函數被調用時傳入的所有參數。arguments
對象是一個類數組對象,它有一個 length
屬性和按數字索引的元素。
每個函數在執行時都會自動創建一個 arguments
對象。我們可以通過arguments去訪問參數。
function exampleFn(a, b, c) {console.log(arguments[0]); // 訪問第一個參數 ,aconsole.log(arguments.length); // 訪問參數的數量, 3console.log(arguments); // 訪問整個 arguments 對象
}exampleFn(1, 2, 3);
arguments
對象不是一個真正的數組,而是一個類數組對象。它沒有數組特有的方法,如 map
或 forEach
。如果需要對 arguments
進行數組操作,可以將其轉換為數組。
//方法1
const argsArray = Array.from(arguments); // 將 arguments 轉換為數組
//方法2
const argsArray = [...arguments]; // 將 arguments 轉換為數組
不過在現代 JavaScript 中,更推薦使用剩余參數去獲取函數的參數。
function exampleFn(...args) {console.log(args); // args 是一個包含所有傳入參數的數組,[1, 2, 3, "four"]console.log(args[0]); // 訪問第一個參數,1console.log(args.length); // 訪問參數的數量,4
}exampleFn(1, 2, 3, "four");
用剩余剩余參數獲取的是一個真正的數組,因此可以使用數組的方法。
function exampleFn(...args) {// args 是一個真正的數組console.log(args);//[1, 2, 3, 4]// 使用 map 方法對每個參數進行操作const squaredValues = args.map(value => value * value);console.log(squaredValues);// [1, 4, 9, 16]
}exampleFn(1, 2, 3, 4);