JavaScript中查找字符串最长单词长度报错问题求助
问题原因分析
- 循环越界错误:数组索引从0开始,
word.length是数组元素总数,循环条件写i <= totalWords时,最后一次循环i等于totalWords,此时word[i]为undefined,访问undefined.length会直接抛出类型错误。 - 变量作用域错误:
max被定义在循环内部,每次循环都会重新初始化,无法累积记录最大长度;同时循环外部的console.log(max)会因max未在函数作用域声明而报错。 - 初始值类型错误:
max初始值设为空字符串'',和数字类型的cmax比较时会发生隐式类型转换,可能导致逻辑判断出错。
修复后的代码
function findLongestWordLength(str) { let word = str.split(" "); console.log(word); let totalWords = word.length; let max = 0; // 移到循环外,初始值设为数字类型的0 for (let i = 0; i < totalWords; i++) { // 将<=改为<,避免数组越界 let cmax = word[i].length; console.log(cmax); if (cmax > max) { max = cmax; } } console.log(max); // 此时max在函数作用域内可正常访问 } findLongestWordLength("The quick brown fox jumped over the lazy dog");
额外优化建议
可以用数组方法简化代码,一行就能得到最长单词长度:
function findLongestWordLength(str) { return Math.max(...str.split(" ").map(word => word.length)); }
内容的提问来源于stack exchange,提问作者Mandeephub
相关产品推荐
相关产品推荐

