我有一个只有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
}
那么最好怎么做呢?
编辑:
对于这个项目,我不能使用typescript,但我认为最好使用@Nick建议的一些typescript术语,以指示未来的人查看我的代码,需要5个参数。如:
// type Elements = [object,object,object,object,object];
const myFunc = (... fruitARR /*:Element*/) => {
}
如果你不想使用…我认为你的替代方案很好,也很简单。
其他选项可以是:
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
}