在函数调用的时候都会传递两个隐式参数:第一个就是上下文对象this,第二个就是封装实参对象arguments。arguments对象有什么作用呢,我们怎么使用呢?下面我们一一讲解
1、可以在函数内部访问所有实参
function demo() {
console.log(arguments[0]) // 1
console.log(arguments[1]) // 5
console.log(arguments[2]) // 6
console.log(arguments[3]) // undefined
}
demo(1,5,6)
2、通过length属性判断实参的个数
function senior() {
console.log(arguments.length)
}
senior(1) // 1
senior('a','r',4) // 3
senior(true,undefined,null,0) // 4
3、正常模式下,arguments对象在使用过程中可以进行修改
function add(a,b) {
arguments[0] = 50
arguments[1] = 100
console.log(a+b) // 150
}
add(3,5)
4、严格模式下,arguments对象在使用中是不可以进行修改的,修改arguments对象不会影响到实际的函数参数
function add2(a,b) {
// 开启严格模式
'use strict'
arguments[0] = 50
arguments[1] = 100
console.log(a+b) // 8
}
add2(3,5)
5、arguments对象不是数组,但是可以通过一些方式,转换成数组,从而使用数组的方法
function foo() {
console.log(arguments) // Arguments(5) [1, 3, 4, 5, 0, callee: ƒ, Symbol(Symbol.iterator): ƒ]
var f = Array.prototype.slice.call(arguments)
// var f = [].slice.call(arguments)
// var f = [...arguments]
// var f = Array.from(arguments)
// 通过以上四种方式的任意一种方式,都可以把arguments对象转换成数组
console.log(f) // [1, 3, 4, 5, 0]
}
foo(1,3,4,5,0)
6、arguments的callee属性可以返回对应的原函数,达到调用自身函数的效果,严格模式下不可用
var calleeFn = function fn() {
console.log(arguments.callee === calleeFn) // true
console.log(arguments.callee === calleeFn2) // false
}
var calleeFn2;
calleeFn()
自从箭头函数出来后,arguments就用的比较少了。因为箭头函数不支持arguments。但是多了解了解底层采用的技术对我们有益无害,加油!