您要解决的问题是“如何在字符串中找到所有符合条件的符号(元音)”
正如@Pogrindis 在他们的评论中提到的,你的 for 循环是不正确的。它遍历元音数组['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] 并检查句子中位置i 处的符号是否是元音。
考虑这个逐步浏览代码:
0. 定义数组vowels 0. 定义函数countVowels
- 调用
countVowels("Hello World')步入函数
sentence === 'Hello World'
-
for(let i=0; i<vowels.length; i++) 请注意,元音是定义在顶部的数组,因此循环将对其进行迭代。 vowels.length == 10 while sentence.length === 11 所以这个循环永远不会到达Hello World 的最后一个符号(如果字符串更长,也可以想象一下)
-
if(vowels.includes(sentence[i])) 检查位置 i 的符号(第一次迭代时为 0,所以 H)是否在 vowels 数组中(不是,所以 false)
-
for 循环继续 i 然后是 1、2、3、4、5、6、7、8 和 9
- 当
i 为1、4 和7 时,count 增加,因为vowels.includes(sentence[i]) 为真。
- 最后当for循环结束时(虽然从未检查最后一个字母),函数返回,但它返回
console.log函数调用的返回值——即undefined
要获得句子中的所有元音,您至少需要进行两次调整:
- 遍历句子,而不是元音数组,以便您始终检查其中的所有字母。
- 您需要将它们打印出来,而不是计算元音。我建议您实际上将它们全部收集到数组中 - 这样就可以轻松计算它们并打印它们。
const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
function getVowels(sentence) {
let vowelsInSentence = [];
for (let i = 0; i < sentence.length; i++) { // iterate over `sentence`
if (vowels.includes(sentence[i])) {
vowelsInSentence.push(sentence[i]);
}
}
return vowelsInSentence; // it is better to return a value, this way code which calls the function can decide what to do with the result
}
console.log(getVowels('Hello World'));
console.log(getVowels('AaEeIiOoUu'));
console.log(getVowels('aaaaa'));
这是相同代码的更高级版本:
const vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']); // set is more efficient data structure for lookups
function getVowels(sentence) {
return sentence
.split('') // this returns an array of all the letters in a string, i.e. ['H', 'e','l','l','o',' ','W','o','r','l','d']
.filter(letter => vowels.has(letter)); // this checks every element of an array to match a condition and returns an array of all elements where the check returned `false`
}
console.log(getVowels('Hello World'));
console.log(getVowels('AaEeIiOoUu'));
console.log(getVowels('aaaaa'));