如何過濾包含函數的數組

盧埃將軍

所以就像我需要在速記或函數中編寫 if/else 語句而不是:
if (hero === "Robin"){return callRobin()}... 或代替 switch case。

const callRobin = () => `Hey Robin`;
const callRaven = () => `Hey Raven`;
const callStarFire = () => `Hey StarFire`;
const callBeastBoy = () => `Hey BeastBoy`;

// these were the functions!!

const herosFuncArr = [callRobin, callRaven, callStarFire, callBeastBoy];  //an array that contains the functions
const herosStringsArr = ['Robin', 'Raven', 'StarFire', 'BeastBoy'];
const myFunc = param => param == herosStringsArr.filter(x => x.includes(param)) ? herosFuncArr.filter(z => z.name.includes(param)()) : false;
myFunc('StarFire');

我在這段代碼中的觀點是:當我們輸入一個英雄名字作為參數時,如果它存在於字符串數組中,則從函數數組中返回一個元素,該元素具有與參數相同的字母作為函數,如雙括號所示

我嘗試了很多東西,也嘗試過 eval (`call${param}()) 但顯然這是不可接受的。也試過 .toString 但沒有用(對我來說)。任何幫助,將不勝感激。

安迪

您最好消除所有這些函數,並創建一個callHero函數,您可以將找到的英雄的名稱傳遞給該函數並返回一個字符串。您無需擔心filter用於find查找第一個匹配項。

而且它最好不要使用includes,因為這將匹配StarStarFire你可能不希望這樣做。只是做一個簡單的比較。

const heroes = ['Robin', 'Raven', 'StarFire', 'BeastBoy'];

// Return a string
function callHero(hero) {
  return `Hey ${hero}!`;
}

function isAHero(name) {

  // Find the hero in the array
  const hero = heroes.find(hero => hero === name);

  // If it exists call the `callHero` function with the hero name
  // and return the resulting string from the function
  if (hero) return callHero(hero);

  // Otherwise return something else
  return `Boo! ${name} is not a hero.`;
}

console.log(isAHero('Robin'));
console.log(isAHero('Billy Joel'));
console.log(isAHero('StarFire'));
console.log(isAHero('Star'));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章