arguments 是函數內部可用的類數組對象,包含調用時傳入的所有實參。理解其特性對編寫靈活函數、實現重載至關重要。
length、索引訪問 [0],但無數組方法 (push, map 等)。arguments[i] 與對應形參雙向同步修改。'use strict'; 下修改不相互影響。arguments.callee 指向當前函數,arguments.caller 指向調用者 (已棄用)。// ES6 展開運算符 (最推薦)
var args = [...arguments];
// Array.from
var args = Array.from(arguments);
// 經典 slice 方案
var args = Array.prototype.slice.call(arguments);
function flexi() {
switch (arguments.length) {
case 0: return 'no args';
case 1: return 'one: ' + arguments[0];
case 2: return 'two: ' + arguments[0] + ', ' + arguments[1];
default: return 'many: ' + Array.prototype.join.call(arguments, ',');
}
}
flexi(); // "no args"
flexi('a'); // "one: a"
flexi('a','b'); // "two: a, b"
flexi(1,2,3,4); // "many: 1,2,3,4"
// 更優雅:參數對象模式
function config(options) {
options = Object.assign({ timeout: 3000, retry: 3 }, options);
// ...
}
config({timeout: 5000});
function test() {
console.log(typeof arguments); // "object"
console.log(arguments instanceof Array); // false
console.log(Array.isArray(arguments)); // false
console.log(arguments.pop); // undefined
}
test(1,2,3);
// ES6: 剩餘參數是真數組
function modern(...args) {
console.log(Array.isArray(args)); // true
console.log(args.map(x => x * 2)); // 直接用數組方法
// arguments 仍可用但不推薦
}
modern(1,2,3);
'use strict';
function strict(a, b) {
arguments[0] = 10;
console.log(a); // 1 (不受影響)
a = 20;
console.log(arguments[0]); // 10 (不受影響)
}
strict(1, 2);