【问题标题】:It is good practice to use name=arguments as function arguments in arrow functions?在箭头函数中使用 name=arguments 作为函数参数是一种好习惯吗?
【发布时间】:2019-09-18 10:41:36
【问题描述】:

箭头函数没有参数数组;使用...arguments 有多好?以后不会弄坏东西吧?

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

【问题讨论】:

  • 使用完全没问题,因为这些都在文档中指定,不用担心
  • 为什么不直接做...args?它在多个级别上更容易混淆,而且更短。
  • 您是在问这个具体案例吗?因为const getStr = (joiner, ...rest) => rest.join(joiner) 会好很多。
  • 我会避免将数组命名为arguments,因为可能会造成混淆。我会给它取个名字,任何不同的名字:例如argsargumentsArray。恕我直言。
  • "箭头函数没有参数数组" 普通函数也没有。一个普通的函数有arguments object - 它不是一个数组,而是一个类似数组的。不同之处在于您不能在其上使用数组方法,例如,function fn() { return arguments.map(x => x+1)} 是不可能的。

标签: javascript arrays string arrow-functions


【解决方案1】:

箭头函数没有自己的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 的参数,如果您在外部函数范围内有箭头函数,它会将 arguments 从外部函数中隐藏起来。

【讨论】:

    猜你喜欢
    • 2015-02-18
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2017-10-11
    • 2014-04-01
    相关资源
    最近更新 更多