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)