You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

查找字符串最长单词长度的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:17:14