arguments对象

arguments对象是所有函数中可用的局部变量。你可以使用arguments对象在函数中引用函数的参数。此对象包含传递给函数的每个参数的条目,第一个条目的索引从0开始。arguments对象仅在函数内部有效,在函数外部调用会出现一个错误。

arguments的属性:

arguments.callee:指向当前执行的函数

arguments.caller:指向调用当前函数的函数

arguments.length:指向传递给当前函数的参数数量

 

1.使用arguments对象,无需明确指出参数名

function sayHi(){
   if(arguments[0] === "bye"){
      return;
   }  
   alert(arguments[0])  
} //第一个参数用arguments[0],第二个参数用arguments[1]以此类推

2.检测参数个数,arguments类似一个数组,但它除了长度之外没有任何数组属性

function howManyArgs(){
  alert(arguments.length);
}
howManyArgs('string',45)  //2
howManyArgs();//0
howManyArgs(12) // 1

3.将arguments转换成一个真正数组

let  args = Array.prototype.slice.call(arguments);

let args = [].slice.call(arguments)

let args = Array.from(arguments)

let args =  [...arguments]

4.模拟函数重载

function doAdd(){
   if(arguments.length === 1){
      alert(arguments[0]+5);
   }  else if(arguments.length === 2){
      alert(arguments[0] + arguments[1])
   }
}

doAdd(10)  //15

doAdd(40,20)  //60

5.arguments的typeof返回'object'

console.log(typeof arguments)  // object

console.log(typeof arguments[0]) // 返回单个参数的typeof

 

posted @ 2017-08-08 08:23  吃草的虾米  阅读(153)  评论(0编辑  收藏  举报