我应该将以下函数变成 while 循环。该函数应该计算某个字符串中出现的所有 e。这是使用 for 循环的函数:
function eCounter(word) {
let count = 0;
for (let index = 0; index < word.length; index++) {
let char = word[index];
if (char === "e" || char === "E") {
count += 1;
}
}
return count;
};
这是我的代码:
function eCounter(word) {
let count = 0
let index = 0;
let char = word[index];
while (char === "e" || char === "E") {
index+= count;
}
return count;
}
};
console.log(eCounter("apple")); // => 1
console.log(eCounter("appleapple")); // => 2
console.log(eCounter("Appleee")); // => 3
如果count和index都为0,并且定义了char,我不知道下一步该怎么做。当我 console.log 字符串时,所有三个都返回零。
我能得到的任何帮助将不胜感激。
我尝试将 for 循环中的所有代码放入 while 循环中。我想如果我将 for 循环代码重新排列成 while 循环,它将返回每个字符串中 e 的数量。但是当我运行代码时,所有三个计数都返回 0。
类似于for循环
function eCounter(word) {
let count = 0
let index = 0;
while (index < word.length) {
const char = word[index]
if (char === "e" || char === "E") {
count++
}
index++
}
return count;
}