JavaScript中第二个实现单词首字母大写的getCapsWords函数存在什么问题
问题原因分析
核心问题是continue的执行逻辑导致循环计数器无法正常自增,最终陷入死循环,具体拆解如下:
两个关键字的行为差异
break:直接终止整个循环的执行,第一个版本遇到Good时直接退出循环,返回之前拼接的Hello World,所以运行正常。continue:仅跳过当前循环剩余的代码,直接进入下一轮循环的条件判断,不会终止整个循环。
第二个函数的死循环触发流程
当循环执行到下标为2的元素(对应单词Good)时:
- 单词处理完成后命中
if (word === "Good") continue逻辑 continue跳过了本轮循环后续的result.push(word)和i++代码- 计数器
i的值永远停在2,循环条件i < words.length永远成立 - 下一轮循环依然取下标为2的元素,再次命中
continue逻辑,无限重复上述过程,程序卡死。
修复方案
如果需求是跳过所有Good单词,保留其余大写后的单词,只需要把计数器自增逻辑移到continue判断之前即可:
function getCapsWords(str) { let result = []; const words = str.split(" "); let i = 0; while (i < words.length) { let word = words[i]; word = word[0].toUpperCase() + word.slice(1); i++; // 先更新计数器,避免触发continue时无法自增 if (word === "Good") continue; result.push(word); } return result.join(" "); }
修改后调用getCapsWords("Hello World Good Good Morning!!!")会返回Hello World Morning!!!,符合预期。
内容的提问来源于stack exchange,提问作者Nava。
相关产品推荐
相关产品推荐

