我应该在字符串中找到最长的单词,这是我到目前为止提出的代码。不幸的是,这似乎不起作用,我的问题是为什么?

function findLongestWordLength(str) {
  str.split("");
  let longest = 1;
  for(let i = 0; i < str.length; i++){
    if (str[i].length > longest){
       longest = str[i].length;
    }
  }
  return longest;
}

最佳答案

如果我没有正确理解,则有两个主要问题:

1)您没有在任何地方存储String.split()的结果。

2)如果需要拆分不同的单词,则需要按space拆分

我也将从longest = 0而不是1开始

例:



function findLongestWordLength(str)
{
    str = str.split(" ");
    let longest = 0;

    for (let i = 0; i < str.length; i++)
    {
        if (str[i].length > longest)
            longest = str[i].length;
    }

    return longest;
}

console.log(findLongestWordLength("Hello World"));
console.log(findLongestWordLength(""));
console.log(findLongestWordLength("123 1234567 12345"));

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}





另外,您可以使用Array.map()将每个单词的长度抄成map的长度,然后在Math.max()上的spread这样的长度数组得到所需的结果:



function findLongestWordLength(str)
{
    let wordLengths = str.split(" ").map(word => word.length);
    return Math.max(...wordLengths);
}

console.log(findLongestWordLength("Hello World"));
console.log(findLongestWordLength(""));
console.log(findLongestWordLength("123 1234567 12345"));

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

关于javascript - 在字符串中找到最长的单词不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55963144/

10-10 17:57
查看更多