倚天杖
2022-10-21 10:50:09
我寫了一個關于在單詞中查找元音的代碼。感謝console.log,我得到了輸出,它可以工作。但是一旦我嘗試返回,它不會返回任何東西..我不明白為什么?這里的代碼:function vowelCount(str) { let word = str.split(""); // console.log(word); // console.log(word.length - 1); let count = 0; for (let i = 0; i <= word.length - 1; i++) { if ( str[i] === "a" || str[i] === "e" || str[i] === "i" || str[i] === "o" || str[i] === "u" || str[i] === "y" ) { count = count + 1; } } // console.log(count); return count;}vowelCount("hello");vowelCount("thereactor");
4 回答

慕斯709654
TA貢獻1840條經驗 獲得超5個贊
確保使用返回的數據。
var vowelsInHello = vowelCount("hello");
console.log(vowelsInHello);

白衣非少年
TA貢獻1155條經驗 獲得超0個贊
這是一個更好的方法
function vowelCount(str) {
let count = 0;
for (let i = 0; i <= str.length - 1; i++) {
var char = str.charAt(i).toLowerCase()
if (
char === "a" ||
char === "e" ||
char === "i" ||
char === "o" ||
char === "u" ||
char === "y"
) {
count++
}
}
return count;
}
console.log(vowelCount('this has some vowels'))
添加回答
舉報
0/150
提交
取消