描述
arguments简单来说,就是存储函数中参数的一个局部变量(注意是非箭头函数),参数按索引为属性名,如第一个参数属性名是0,第二个参数属性名是1,第三个参数熟悉名是3,如
function a(){
console.log(arguments[0])
console.log(arguments[1])
console.log(arguments[2])
}
a(1,2,3)
// 输出:
// 1
// 2
// 3
但注意它是一个类数组对象,何谓类数组对象?就是像数组一样的对象 。
看下代码即可知道他们的区别
可以看到,arguments的 _proto_ 指向的是 object,所以虽然看起来跟数组很像,有索引,有length,但不是数组,只是一个类数组对象,所以本身就没有数组原型上的那一堆方法了。
当然有时候计算需要,要转换成真实数组也可以直接用 Array.from()方法或者扩展运算符
const argsArrayFrom = Array.from(arguments);
const args = [...arguments];
例子
知道原理后,利用 arguments 可以按需求实现很多东西
遍历参数求
function add(){
let sum = 0,len = arguments.length
for(;len--;){
sum += arguments[len]
}
console.log(sum)
return sum
}
add(1,2,3) //6
自定义连接字符串函数
function strConcat(sp){
const args = Array.prototype.slice.call(arguments,1)
return args.join(sp)
}
const c1 = strConcat(';','1','2','3')
console.log(c1) //"1;2;3"
const c2 = strConcat('&','1','2','3')
console.log(c2) //"1&2&3"
手写实现 bind
[待补充]
浏览器兼容
兼容性还是挺全的,但 callee 和 @@iterator 就不建议使用了,在严格模式下callee已被移除