【问题标题】:How to Create an Array from the Arguments in an Arrow Function如何从箭头函数中的参数创建数组
【发布时间】:2021-10-02 00:26:20
【问题描述】:

我有一个正好有 5 个参数的箭头函数; fruit1fruit5。我想明确表示它仅限于这 5 个参数,所以我不想使用 ... rest

但是,在函数中,我需要从这五个参数创建一个数组。

const myFunc = (fruit1, fruit2, fruit3, fruit4, fruit5) => {
    let arr = [... arguments];
    // Other stuff follows
}

有参数未定义的错误(因为箭头函数中不存在参数)。

另一种选择

const myFunc = (fruit1, fruit2, fruit3, fruit4, fruit5) => {
    let arr = [fruit1, fruit2, fruit3, fruit4, fruit5];
    // Other stuff follows
}

很麻烦。

Rest 并没有明确说明使用该代码的其他程序员必须正好有 5 种水果:

const myFunc = (... rest) => {
    let arr = [... rest]; // A copy of the array
    // Other stuff follows
}

那么最好的做法是什么?

编辑:

对于这个项目,我不能使用打字稿,但我认为最好使用@Nick 建议的一些打字稿术语,以向未来查看我的代码的人表明需要 5 个参数。例如:

// type Elements = [object,object,object,object,object];
const myFunc = (... fruitARR /*:Element*/) => {
}

【问题讨论】:

  • 您的第二个选项似乎最好。它很冗长,但它可以完成您需要它做的事情。或者转移到打字稿,你可以很容易地执行这个:typescriptlang.org/play?#code/…
  • "我有一个正好有 5 个参数的箭头函数;fruit1fruit5" - 你永远不应该枚举你的变量名。始终使用数组代替。还是它们实际上是不同类型的论点?你拿水果做什么?为什么需要将它们放在一个数组中?为什么你需要正好 5 个值?你的实际代码是什么?如果不回答所有这些问题,我们就无法给出适当的建议。
  • 备选方案 3:function myFunc(...arr) { if (arr.length != 5) throw new RangeError("Needs 5 arguments for some reason"); … }

标签: javascript arguments arrow-functions


【解决方案1】:

如果您不想使用 ...rest,我认为您的替代选择既好又简单。

其他选项可以是:

const myFunc = (fruits) => {
  if(!Array.isArray(fruits) || fruits.length != 5){
    alert("Is not array or not are 5 elements);
    throw "Error";     
  }
  // then fruits is your array
  // Other stuff
}

【讨论】:

  • 我相信他们正在寻找可以显示函数期望多少参数的东西......这不是很直观。
  • 那么最好的办法就是使用Typescript
猜你喜欢
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多