js函数接收不定量参数并求和

博客介绍了JS函数接收的参数会默认存于arguments命名参数中,arguments是伪数组。它只能用数组循环遍历方法,不能用push、pop等方法,若要使用数组其他方法,可通过Array.prototype.slice.call(arguments)将其转为真正的数组。

js函数接收的参数会默认放置到arguments命名参数中,arguments对象我们实际称为伪数组:

function Sum (a,b){
     console.log(a)//1
     console.log(b)//2

     var len = arguments.length;
     console.log(len);//5
     console.log(arguments);

     var sum = 0;
     for(var i=0;i<arguments.length;i++){
         sum = sum + arguments[i]
     }
     console.log(sum)//15
}
Sum(1,2,3,4,5)

arguments打印输出:

注意: 

伪数组不是真正的数组,它只能使用数组的循环遍历方法,但是不能使用数组push,pop等方法,如果想使用数组的一些方法的话,就先将伪数组转化为真正的数组Array.prototype.slice.call(arguments):

function Sum (a,b){

   // 将伪数组转化为真正的数组,以便于使用数组的push,pop等方法
   var args = Array.prototype.slice.call(arguments);

   console.log(args)//[1,2,3,4,5]

}
   Sum(1,2,3,4,5)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值