重载(overload)

112 阅读1分钟

重载(overload):

  • 当一个函数不知道要传入几个形参时,都可以用arguments(是一个类数组对象,js自带的)接住所有的实参值;
//求和
function add(){
  var total=0;
  for(var num of arguments){
    total+=num;
  }
  return total;
}
console.log(add(1,2,3));//6
console.log(add(5,6,7,8));//26