JS forEach断点调试问题:计算字符串最后一个单词长度时数组不更新
问题原因
你的代码存在3处逻辑漏洞:
- 仅统计了两个相邻空格之间的字符长度,遗漏了字符串开头到第一个空格、最后一个空格到字符串末尾这两段的长度统计,导致首尾的单词不会被计入
- 遍历spaces数组时i取到了最后一位,此时
spaces[i+1]为undefined,计算得到的差值为NaN,会干扰后续过滤逻辑 - 当字符串中没有空格时,spaces数组为空,后续统计逻辑完全不会执行,会错误输出0
修复后的代码
function lengthOfLastWord(s) { let spaces = []; let space = ' '; let spaceInd = s.indexOf(space); while (spaceInd != -1) { spaces.push(spaceInd); spaceInd = s.indexOf(space, spaceInd + 1); } // 新增:在空格索引列表首尾补充虚拟边界,覆盖开头、结尾的字符段 spaces.unshift(-1); spaces.push(s.length); let nonSpaces = []; let wordArray = []; // 修改:循环终止条件调整,避免i+1越界 for(let i = 0; i < spaces.length - 1; i++) { nonSpaces.push((spaces[i + 1] - spaces[i]) - 1); } nonSpaces.forEach(function(number) { if (number >= 1) { wordArray.push(number); } }) if (wordArray.length === 0) { console.log(0); } else { console.log(wordArray[wordArray.length - 1]); } }; lengthOfLastWord("this is my test string"); // 输出6,符合预期
改动说明
- 通过
unshift(-1)在空格列表开头加虚拟左边界,把字符串开头到第一个空格的段纳入统计 - 通过
push(s.length)在空格列表结尾加虚拟右边界,把最后一个空格到字符串末尾的段纳入统计 - 把for循环的终止条件从
i<spaces.length改为i<spaces.length -1,避免访问不存在的spaces[i+1]产生NaN
内容的提问来源于stack exchange,提问作者McKay Anhder
相关产品推荐
相关产品推荐

