简单的JavaScript回调混淆映射()

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

我刚刚进入javascript回调,试图实现一个简单的元音计数功能。这就是我所拥有的,但我无法弄清楚这个回调的语法错误。我确定这是一个非常明显的错误,但是如果有人能够启发我,那就太好了。

function isitVowel(letter){
   return letter in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
}

function countVowels(line){
   return line.split(",").filter(isitVowel).length;
}

countVowels("a,b,c,d,e");
javascript
4个回答
4
投票

我认为你没有正确使用the in operator。它看起来更像你想要check if the value is in the array,你可以使用the includes function

function isitVowel(letter){
    return ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'].includes(letter);
}

注意:检查浏览器兼容性。您可能需要为IE包含​​polyfill。

另请注意:这不是您正在使用的“回调”。您只是将函数引用作为参数传递给另一个函数。 “回调”是在完成异步操作后传递以供使用的函数。


1
投票

你的问题是基于对in的误解。 in在对象中查找键,而不是数组中的值。

相反,你需要使用Array.prototype.includes(),或者,对于较旧的浏览器支持,Array.prototype.indexOf()

return myarray.includes(letter);

要么

return myarray.indexOf(letter) != -1; //-1 means not found

...其中myarray是你的字母数组。


0
投票

你检查字母是否在数组内是不起作用的回调应该没问题。您可以使用

return ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'].includes(letter)

代替


0
投票

Map()

以下演示使用:


演示

let str = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`;

const countVowels = line => {
  // Map of vowels
  let vowels = new Map([['a', 0], ['e', 0], ['i', 0], ['o', 0], ['u', 0], ['A', 0], ['E', 0], ['I', 0], ['O', 0], ['U', 0]]);
  
  /*
  .split('') the input at each character
  .forEach() letter...
  ...if the Map has the letter...
  ...get the value of matching letter from Map...
  ...increment the value...
  ...then set the new value into the same letter.
  */
  line.split('').forEach(letter => {
    if (vowels.has(letter)) {
      let qty = vowels.get(letter);
      qty++;
      vowels.set(letter, qty);
    }
  });
  // Convert the Map into a 2D array 
  return JSON.stringify(Array.from(vowels));
}
// Log the return of countVowels(str)
console.log(countVowels(str));
© www.soinside.com 2019 - 2024. All rights reserved.