簡體   English   中英

為什么第二個代碼與第一個代碼的工作方式不同?

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

第一個代碼正確運行並顯示正確答案 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");

下面的第二個代碼只在單詞“super-long”之前有效,並將10記錄為最終的 output,這是不正確的。 我想弄清楚這里出了什么問題。 它適用於其他句子,

以供參考

句子中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可能在循環結束時持有一個非零值,它將被忽略。 只需在循環末尾添加一個檢查以更新該值。

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;

為了得到 19,你必須以空格結束你的字符串。 因為"otorhinolaryngology"的最后一個字符是'y' ,所以您只需在最后增加 count 並且您永遠不會遇到將更新為高的else條件。 在末尾放一個空格,添加一個額外的條件檢查 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