简体   繁体   English

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

[英]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.第一个代码正确运行并显示正确答案 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.下面的第二个代码只在单词“super-long”之前有效,并将10记录为最终的 output,这是不正确的。 I'm trying to figure out what goes wrong here.我想弄清楚这里出了什么问题。 It works fine with other sentences,它适用于其他句子,

FOR REFERENCE以供参考

The str.length in the sentence is 60(spaces included), and there are 9 spaces in between the entire sentence句子中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");

count could be holding a non-zero value at the end of the loop, which will get ignored. count可能在循环结束时持有一个非零值,它将被忽略。 Just add a check at the end of the loop as well to update that value.只需在循环末尾添加一个检查以更新该值。

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;

In order to get 19, you have to end your string with a space.为了得到 19,你必须以空格结束你的字符串。 Because the last character of "otorhinolaryngology" is a 'y' , you simply increment count at the very end and you never hit your else condition which will update high.因为"otorhinolaryngology"的最后一个字符是'y' ,所以您只需在最后增加 count 并且您永远不会遇到将更新为高的else条件。 Put a space at the end, add an extra condition checking if i == str.length -1 Or simply use the length algorithm, or, as I would prefer, use a reducer like so:在末尾放一个空格,添加一个额外的条件检查 if i == str.length -1或者简单地使用长度算法,或者,如我所愿,使用像这样的 reducer:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM