JS:arguments

在JS的function函数体(仅限function函数,不包括箭头函数)内,可以通过argument类数组对象来访问该函数的全部参数:

function func(a,b,c){
    console.log(a,b,c)
    console.log(arguments[0],arguments[1],arguments[2])
    console.log(arguments.length)
}

func('a','b','c')
// a b c
// a b c
// 3

可以看到arguments由传递到函数中的参数组成,值和数量完全一致,需要注意以下几种情况:

function func(a,b,c){
    console.log(arguments[0],arguments[1],arguments[2],arguments[3])
    console.log(arguments.length)
}

func('a','b')
// a b undefined undefined
// 2

func('a','b','c')
// a b c undefined
// 3

func('a','b','c','d')
// a b c d
// 4

console.log(func.length)
// 3

可以看到arguments是有函数调用时传递的参数决定的,即使函数中没有定义的参数通过arguments也能取到,而通过获取function的length属性取得的值始终等于函数定义的参数个数,与调用无关。下面的代码将尝试修改arguments并观察参数变化:

function func(a,b,c){
    arguments[0]++
    arguments[1]++
    arguments[2]++
    console.log(a,b,c)
}

func(1,2,3)
// 2 3 4

可以看到当修改arguments时,使用形参取得的参数值也发生了改变,这说明arguments中的元素与函数调用时形参所对应的实参指向的是同一个内存地址,但是需要注意以下情况:

function func(a,b,c){
    arguments[0] = 1
    arguments[1] = 2
    arguments[2] = 3
    console.log(a,b,c)
}

func()
// undefined undefined undefined

可以看到,如果调用函数时没有传递参数,通过修改arguments是无法将参数值同步给形参取得的。

由于arguments是一个类数组对象,所以并不具备数组的方法,使用时需要通过call或apply调用数组原型中的方法:

function func(a,b,c){
    /*
    let A = arguments.slice(0,1) // 报错 
    let B = arguments.slice(1,2)  // 报错
    let C = arguments.pop() // 报错
    */
    
    let A = Array.prototype.slice.call(arguments,0,1) // a
    let B = Array.prototype.slice.apply(arguments,[0,1]) // b
    let C = Array.prototype.pop.call(arguments) // c

    console.log(A,B,C)
    console.log(arguments.length)
}

func(1,2,3)
// [1] [2] 3
// 2

同时arguments还具备一个callee属性,指向函数自身,可以用来实现匿名函数递归:

function func(a,b,c){
    console.log(a,b,c)
    Array.prototype.pop.call(arguments)
    if(arguments.length){
        arguments.callee.apply(null,arguments)
    }
}

func(1,2,3)
// 1 2 3
// 1 2 undefined
// 1 undefined undefined

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值