简体   繁体   中英

I need to find how many vowels are in each string of the array using loops. Can't see what I'm doing wrong

So for a course task I need to iterate through an array of fruits to find out how many vowels and consonants are in a word. For the task it says I need to use for-in, for loops and either case-switch or nested-if statements. Here is the code I have:

 const fruits = ["Apple", "Orange", "Banana", "Pear", "Peach", "Strawberry", "Cherry", "Acai"]; for (let fruit in fruits) { var vowels = 0; var consonants = 0; for (var i = 0; i < fruit.length; i++) { switch (fruits[fruit][i]) { case "A": case "E": case "I": case "O": case "U": case "a": case "e": case "i": case "o": case "u": vowels = vowels + 1; break; default: consonants = vowels + 1; break; } } } console.log(`Apple has ${vowels} vowels and ${consonants} consonants`);

I'm pretty new to JS and I just can't seem to see what I'm doing wrong.

One thing to note is that for-in is for objects, where as for-each is used for arrays. Although it seems that you need to use specific functions for this particular bit, thought I would point this out for future use.

What you are essentially doing with your code is setting each element in the array to an object. For instance each variable becomes:

0:"Apple", 1:"Orange", ...

So if we are iterating through, each fruit would have a length of 1.

The answer to you issue is to look at how you have created your for loop compared to how you are creating your switch case. What you really want is not the length of fruit , but the length of fruits[fruit] if that makes any sense. For example:

for (var i = 0; i < fruits[fruit].length; i++) {
      switch (fruits[fruit][i]){
        ...
      }
}

--

Another issue I can see is the way you are tracking your constants. You probably shouldn't have your constants being updated as constants = VOWELS +1 .

--

The last thing I have noticed is that your console.log at the end will not actually be outputting information regarding apples, it will actually be outputting the iniformation about the last fruit in the fruits array (ie Acai )

A possible solution could be with regex.

  1. first you match the vowels
  2. with the output you can dynamically generate a regex.
  3. then you can remove the vowels from the string in order to get the consonats.
const regex = /([aeiou])/gi;
    
const fruits = ["Apple", "Orange", "Banana", "Pear", "Peach", "Strawberry", "Cherry", "Acai"];
    
const map = fruits.reduce((map, fruit) => {
      const vowels = fruit.match(regex);
      const consonats = fruit.replaceAll(new RegExp(`(${vowels.join("|")})`, "ig"), "");
      map[fruit] = { vowels, consonats: consonats.split("") }
      return map;
    }, {})

console.log({ map });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM