简体   繁体   English

如何检查字符串字符是否在 JavaScript 数组中?

[英]How to check if a string character is in a JavaScript array?

I'm trying to make a JavaScript function that tells how many times a vowel was repeated in a given string.我正在尝试制作一个 JavaScript function 来告诉一个元音在给定字符串中重复了多少次。

Here's what I have tried:这是我尝试过的:

    function checkVowel(str) {
    vowels = ['a', 'e', 'i', 'o', 'u']
    str = "hello world"
    
    for(let i = 0; i < str.length; i++){
        if(str[i].includes(vowels)){
            console.log("worked")
        } else {
            console.log("not worked")
        }
    }
}
checkVowel()

How can I make this function check for each vowel rather than the entire array at once?我怎样才能让这个 function 一次检查每个元音而不是整个数组?

Is it this what you're looking for?这就是你要找的吗?

 function checkVowel(str) { const counts = Object.seal({ a: 0, e: 0, i: 0, o: 0, u: 0 }); for (let char of str) { counts[char.toLowerCase()]++; } return counts; } console.log(checkVowel("hello world"));

Another solution另一种解决方案

 function countVowel(word) { const vowels = ["a", "e", "i", "o", "u"]; const wordArray = word.split("").map((s) => s.toLowerCase()); const result = { a: 0, e: 0, i: 0, o: 0, u: 0 }; return wordArray.reduce((acc, curr) => { if (vowels.includes(curr)) { ++acc[curr]; } return acc; }, result); } console.log(countVowel("Angel"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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