查找字符串最长单词长度的JavaScript代码问题排查
问题分析与修复方案
核心错误
你的代码无法运行的原因是循环边界设置错误:
for循环条件写的是i<=words.length,但数组的索引从0开始,最后一个元素的索引是words.length - 1。当i等于words.length时,words[i]会是undefined,此时访问undefined.length会直接抛出Cannot read properties of undefined (reading 'length')的错误。
修复后的代码
把循环条件改为i < words.length即可正常运行:
function findLongestWordLength(str) { let words = str.split(" "); let bigword = 0; for(let i = 0; i < words.length; i++) { if(words[i].length > bigword) { bigword = words[i].length; } } return bigword; }
可选优化方案
如果想让代码更简洁,可以用数组内置方法实现:
- 使用
reduce方法:
function findLongestWordLength(str) { return str.split(" ").reduce((maxLen, word) => Math.max(maxLen, word.length), 0); }
- 结合
map和Math.max:
function findLongestWordLength(str) { const lengths = str.split(" ").map(word => word.length); return Math.max(...lengths); }
内容的提问来源于stack exchange,提问作者Dujmex
相关产品推荐
相关产品推荐

