为什么第二个代码与第一个代码的工作方式不同?

Why doesn't the second code work the same as the first code?

The First Code works correctly and displays the right answer which is 19.

function findLongestWordLength(str) {
  let high = 0;
  let word = str.split(" ");
  
  for(let i = 0; i < word.length; i++)
  {
   if (word[i].length > high)
      high = word[i].length;
  }
  console.log(high)
}

findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

The second code below, only works until the word "super-long" and logs 10 as the final output, which is incorrect. I'm trying to figure out what goes wrong here. It works fine with other sentences,

供参考

句子中的str.length是60个(含空格),整个句子中间有9个空格


function findLongestWordLength(str) {
  let high = 0;
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] != " ") {
      count++;
    } else {
      if (count >= high)
        high = count;
      count = 0;
    }
  }
  return high;
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

为了得到 19,您必须以 space 结束您的字符串。因为 "otorhinolaryngology" 的最后一个字符是 'y',您只需在最后增加计数,而您永远不会达到将更新为高的 else 条件。在末尾放置一个 space,添加一个额外的条件检查是否 i == str.length -1 或者简单地使用长度算法,或者,如我所愿,使用像这样的缩减器:

const findLongestWordLength = str => str.split(' ').reduce((acc, word) => word.length > acc ? word.length : acc, 0)

count 可能在循环结束时持有一个 non-zero 值,该值将被忽略。只需在循环末尾添加一个检查以更新该值。

for(let i = 0; i < str.length; i++)
  {
    if (str[i] != " ") count++;
    else 
    {
      if(count >= high) high = count;
      count = 0;
    }
  }
if(count >= high) high = count;