javascript 有没有一种方法可以使用for循环来标识数组中的某些变量?

kokeuurv  于 2023-02-21  发布在  Java
关注(0)|答案(2)|浏览(97)

我必须开发代码来读取数组中的每个选项,同时计算每个选项中的元音和辅音,这也需要在控制台中打印出来。

let vowels = 0;
let consonants = 0;
const fruits = ["Apple", "Orange", "Pear", "Peach", "Strawberry", "Cherry", "Acai"];

for (let fruit in fruits) {
    console.log(fruits[fruit]);
    if (fruits[fruit] == "a" || fruits[fruit] == "e" || fruits[fruit] == "i" || fruits[fruit] == "o" || fruits[fruit] == "u") {
        vowels + 1;
    }
    else {
        consonants + 1;
    }
}

这是我目前所拥有的,有人能解释一下我遗漏了什么吗?一旦我在Visual Studio代码中运行它,控制台仍然显示数组中的所有选项,而不注册变量的元音或辅音是否被寻址或增加:
编辑:我需要对数组中的每个单词计数,并显示每个单词中有多少个元音和辅音。

[Running] node "d:\coding.js"
Apple
Orange
Pear
Peach
Strawberry
Cherry
Acai

[Done] exited with code=0 in 0.128 seconds
czq61nw1

czq61nw11#

我在代码中添加了更多console.logs,并使用了另一个变量letter
你是想每个单词只看一个字母,还是需要计算每个单词中的每个字母?

let vowels = 0;
    let consonants = 0;
    const fruits = ["Apple", "Orange", "Pear", "Peach", "Strawberry", "Cherry", "Acai"];
    
    for (let word of fruits) {
        console.log("working on word", word);
    
        letter = word[0];   // this is probably wrong, do you need to check EVERY letter of a word?
    
        console.log("  looking at letter", letter);
    
        if (letter == "a" || letter == "e" || letter == "i" || letter == "o" || letter == "u") {
            vowels + 1;
        }
        else {
            consonants + 1;
        }
        console.log("  up to now i found", vowels, "vowels and", consonants, "consonants");
    }

你写了你需要计算每个字母,所以我们需要另一个循环来遍历当前单词的每个字母:

let vowels = 0;
        let consonants = 0;
        const fruits = ["Apple", "Orange", "Pear", "Peach", "Strawberry", "Cherry", "Acai"];
        
        for (let word of fruits) {
            console.log("working on word", word);
            
            for (let letter of word.split('')) {

              console.log("  looking at letter", letter);

              if (letter == "a" || letter == "e" || letter == "i" || letter == "o" || letter == "u") {
                  vowels += 1;
              }
              else {
                  consonants += 1;
              }
              console.log("  up to now i found", vowels, "vowels and", consonants, "consonants");
            
            }
        }

这仍然不计算大写字母。但我相信你可以解决这个问题。

i2loujxw

i2loujxw2#

const fruits = ["Apple", "Orange", "Pear", "Peach", "Strawberry", "Cherry", "Acai"];

const vowels = fruits.flatMap(i=>[...i.toLowerCase()])
  .filter(c=>'aeiou'.includes(c)).length;

const consonants = fruits.join('').length - vowels;

console.log(vowels, consonants)

或者使用regex,感谢Dave在下面的评论:

const fruitsString = ["Apple", "Orange", "Pear", "Peach", "Strawberry", 
  "Cherry", "Acai"].join('')

const vowels = fruitsString.match(/[aeiou]/ig).length

const consonants = fruitsString.length - vowels

console.log(vowels, consonants)

相关问题