arguments 是类数组,不是真数组;它存在于函数中;数据来源于,函数调用时传入的所有参数。我们直接把arguments打印出来,深刻了解下它的概念和特性。
如图,函数调用三次,每次传入不同数量的参数,arguments跟着改变。可以看出基本特性如下:
1. 自动存在于所有函数中(箭头函数除外),函数内部可以直接访问,无需声明。
2. 包含所有传入参数:无论这些参数是否有对应的形参。
3. 类数组对象:不是真数组,仅具有 length 属性和索引元素(arguments[0], arguments[1], arguments[2]),没有数组方法(如 forEach, map 等)。
实际应用示例
1.转换为真数组
function convert() {
var arr = Array.prototype.slice.call(arguments);
console.log(arr);
}
convert('orange','apple')
// 输出结果为真数组 [ 'orange', 'apple' ]
2. 创建灵活的构造函数
function Person() {
this.name = arguments[0] || 'Anonymous';
this.age = arguments[1] || 0;
}
const p1 = new Person('Alice', 25);
const p2 = new Person(); // 使用默认值
3. 实现函数重载效果
function display() {
if (arguments.length === 1) {
console.log(`Name: ${arguments[0]}`);
} else if (arguments.length === 2) {
console.log(`Name: ${arguments[0]}, Age: ${arguments[1]}`);
}
}
display('Alice'); // Name: Alice
display('Bob', 30); // Name: Bob, Age: 30
虽然 arguments 仍然可用,但 ES6 引入了更好的替代方案:剩余参数。
上一篇:js数组常用方法归类,更利于记忆
下一篇:js剩余参数详解