如何从箭头函数中的参数创建数组[重复]

问题描述 投票:0回答:1

我有一个只有 5 个参数的箭头函数;

fruit1
fruit5
。我想澄清一下,它仅限于这 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*/) => {
}
javascript arguments arrow-functions
1个回答
0
投票

如果您不想使用...休息,我认为您的替代选择很好而且简单。

其他选项可以是:

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
}
© www.soinside.com 2019 - 2024. All rights reserved.