Simple JavaScript Callback Confusion

问题: I'm just getting into javascript callbacks, trying to implement an easy vowel counting function. This is what I have, but I can not figure out what is syntactically wrong w...

问题:

I'm just getting into javascript callbacks, trying to implement an easy vowel counting function. This is what I have, but I can not figure out what is syntactically wrong with this callback. I'm sure this is a very obvious error, but if anybody could enlighten me, that would be great.

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");

回答1:

I don't think you're using the in operator correctly. It looks more like you want to check if the value is in the array, for which you might use the includes function:

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

Note: Check browser compatability. You may need to include the polyfill for IE.

Also note: This isn't really a "callback" that you're using. You're simply passing a function reference as a parameter to another function. "Callbacks" are functions passed for use after completing an asynchronous operation.


回答2:

Your problem is based on a misunderstanding of in. in looks for a key within an object, not a value in an array.

Instead you need to use Array.prototype.includes() or, for older browser support, Array.prototype.indexOf().

return myarray.includes(letter);

or

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

...where myarray is your letters array.


回答3:

Your check if the letter is inside the array doesn't work the callback should be fine. You can use

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

instead


回答4:

Map()

The following demo uses:

  • Map() to store the vowels

  • .split('') to separate the string input into an array of letters.

  • .forEach() to iterate through the input string.

  • Map() methods .has(), .get(), and .set() were used on each iteration to compare and store matches.

  • Array.from() was used to convert Map() into a 2D array.


Demo

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));

  • 发表于 2019-03-01 03:02
  • 阅读 ( 145 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除