1、arguments只能在函数内使用,在函数外是undefined,同时arguments是一个对象,只是恰好属性名是数字,刚好可以使用数组的下标。或者理解为类数组,有数组的length属性和下标取值属性,仅此而已。
funtion fn(a,b,c,d){ console.log(Array.isArray(arguments)) // false 表示不是数组 // arguments 形式 arguments = { 0:a, 1:b, 2:c, 3:d, length: 4 } }
2、callee的作用,callee指向的是当前正在执行的函数,可以作用于匿名函数的递归
// callee: 指向当前正在执行的函数 function fn3(x) { if(x<2) return 1 return x*arguments.callee(x-1) } x = fn3(5) // 5 4 3 2 1 = 120 console.log(x) //120 y = (function(x){ if(x<2) return 1 return x*arguments.callee(x-1) }(5)) console.log(y) //120
3、length,length从调用函数开始就已经固定,不会改变。
let arr2 = [1,2] arr2[2] = 3 arr2[3] = 4 console.log(arr2.length) // 4 function fn4(a,b,d){ arguments[5] = 6 arguments[6] = 7 console.log(arguments.length) // 5, 代表的是实际值,实参个数 console.log(arguments.callee.length) // 3, 代表的是期望值,形参个数 // throw new Error('出错') // 报错,不会往下执行 } fn4(1,2,3,4,5)
4、剩余参数、解构赋值和默认值的影响
// 无默认参数,剩余参数和解构赋值 function fn7(a){ console.log(a,arguments[0]) // 2,2 a = 1 console.log(arguments[0]) // 变为1,arguments[0] 和a绑定了,也就是实参和形参指向同一个地址 } fn7(2) function fn8(/*...args*/args = 22){ arguments[0] = 1 console.log(arguments,args) // [1],22 } fn8(3)
5、arguments转真正的数组
// 转为真正的数组 var arr = Array.prototype.slice.call(arguments) arr = [].slice.call(arguments) arr = Array.from(arguments) arr = [...arguments]