好的做法是在箭头函数中使用name = arguments作为函数参数?

时间:2019-09-18 10:41:36

标签: javascript arrays string arrow-functions

箭头函数没有参数数组;使用...arguments有多好?将来不会破坏什么吗?

const getStr = (...arguments) => [].slice.call(arguments, 1).join(arguments[0])
getStr( '*', '1', 'b', '1c' ) // '1*b*1c'

1 个答案:

答案 0 :(得分:3)

箭头函数本身没有arguments,因此使用arguments作为参数不是问题,但可能会造成混淆。

但是外部函数范围内的箭头函数可以访问外部函数的arguments对象。因此,箭头函数可以在其逻辑中使用外部函数的arguments,如下所示:

const getStr = (...anotherArguments) => { 
  console.log("arguments here is ", typeof arguments); 
  return [].slice.call(anotherArguments, 1).join(anotherArguments[0]);
}
console.log(getStr( '*', '1', 'b', '1c' ));


function outer(){
  //arguments captured from the outer function scope
   return (() => { 
      console.log("arguments here is" , typeof arguments); 
      return [].slice.call(arguments, 1).join(arguments[0]); 
   })()
}
console.log(outer( '*', '1', 'b', '1c' ));

因此,如果箭头函数中有一个名为arguments的参数,则如果外部函数作用域中有arrow函数,它将使arguments不受外部函数的影响。