簡體   English   中英

如何檢查字符串字符是否在 JavaScript 數組中?

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

我正在嘗試制作一個 JavaScript function 來告訴一個元音在給定字符串中重復了多少次。

這是我嘗試過的:

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

我怎樣才能讓這個 function 一次檢查每個元音而不是整個數組?

這就是你要找的嗎?

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

另一種解決方案

 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