使用此代码在JS中查找字符串中最长的单词?

请让我知道这段代码有什么问题:


我知道有更简单的方法可以实现预期的结果,但是我想了解如何运行此特定代码,以及我的错误是什么。尝试尽可能少地改变它,否则让我知道为什么这行不通。另请注意,我正在尝试使用console.log3 个值,而不仅仅是一个。谢谢你。


编辑:这是我实际测试代码是否有效的 freeCodeCamp 练习:https ://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-最长的字符串中的单词出于某种原因,大多数答案在这里的片段中有效,但在 freeCodeCamp 练习控制台中无效?


function findLongestWordLength(str) {


  let arr = [];

  let longestWord = "";

  let longestNum = 0;


/*If there is a character at str[i] add it to the arr, else if there is whitespace

don't add it to the arr. Instead, find the arr.length, if is greater than the

previous overwrite longestNum, longestWord and empty the 

arr, if not just empty the arr and keep going*/


  for (let i = 0; i <= str.length - 1; i++) {

    if (/./i.test(str[i])) {

      arr.push(str[i]);

    } else if (/\s/.test(str[i])) {

      if (arr.length - 1 >= longestNum) {

        longestNum = arr.length - 1;

        longestWord = arr.join("");

        arr = [];

      } else {

        longestNum = longestNum;

        longestWord = longestWord;

        arr = [];

      }

    }

  }

  console.log(arr);

  console.log(longestWord);

  console.log(longestNum);

  return longestNum;

}


  findLongestWordLength("The quick brown fox jumped over the lazy dog");


qq_花开花谢_0
浏览 180回答 3
3回答

小怪兽爱吃肉

只要字符不是空格(/\S/- 大写 S),您就需要添加项目。如果是空格,则需要将长度与前一个 进行比较longestWord.length,并将单词分配给longestWord。在空间的情况下,你 init arr。注意:赋值longestNum = longestNum; longestWord = longestWord;是多余的,它们已经等于自己了。此外, thelongestNum也是多余的,因为它是从longestWord( longestWord.length)派生而来的。function findLongestWordLength(str) {&nbsp; let arr = [];&nbsp; let longestWord = "";&nbsp; for (let i = 0; i < str.length; i++) {&nbsp; &nbsp; if (/\S/.test(str[i])) { // as long as it's not a space&nbsp; &nbsp; &nbsp; arr.push(str[i]);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; if (arr.length > longestWord.length) {&nbsp; &nbsp; &nbsp; &nbsp; longestWord = arr.join("");&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; arr = [];&nbsp; &nbsp; }&nbsp; }&nbsp; return longestWord.length;}var result = findLongestWordLength("The quick brown fox jumped over the lazy dog");console.log(result);

ibeautiful

我假设/./i.test(str[i])您正在尝试匹配除空格之外的所有内容。.匹配除换行符以外的所有内容,因此我将其切换为[^\s]实际匹配除空格以外的所有内容。我还将控制台日志放在循环之外,因此输出有些可读。function findLongestWordLength(str) {&nbsp; let arr = [];&nbsp; let longestWord = "";&nbsp; let longestNum = 0;&nbsp; for (let i = 0; i <= str.length - 1; i++) {&nbsp; &nbsp; if (/[^\s]/i.test(str[i])) {&nbsp; &nbsp; &nbsp; arr.push(str[i]);&nbsp; &nbsp; } else if (/[\s]/i.test(str[i])) {&nbsp; &nbsp; &nbsp; if (arr.length > longestNum) {&nbsp; &nbsp; &nbsp; &nbsp; longestNum = arr.length;&nbsp; &nbsp; &nbsp; &nbsp; longestWord = arr.join("");&nbsp; &nbsp; &nbsp; &nbsp; arr = [];&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; longestNum = longestNum;&nbsp; &nbsp; &nbsp; &nbsp; longestWord = longestWord;&nbsp; &nbsp; &nbsp; &nbsp; arr = [];&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; console.log(arr); // last word since you reset arr every step&nbsp; console.log(longestWord);&nbsp; console.log(longestNum);&nbsp; return longestNum;}findLongestWordLength("The quick brown fox jumped over the lazy dog");一个更好的方法是:function findLongestWordLength(sentence) {&nbsp; const words = sentence.split(' ');&nbsp; return words.reduce((max, currentWord) => max > currentWord.length ? max : currentWord.length, 0);}

开满天机

只需进行最少的修改,您就需要进行这些更改:确保最后一个字的长度也得到验证。目前不是。为此,您可以在执行循环之前向输入字符串添加一个空格。更改 test&nbsp;/./i,因为它将匹配除换行符以外的任何内容。您需要检查字母,可能还有数字,可能还有下划线,但不是标点符号。所以/\w/会有所改善。你可以想到更好的正则表达式。浏览器正在慢慢支持/\p{L}/u,它可以匹配任何字母表中的字母。else应该删除 中的测试,因为您只想无条件地处理这里的任何其他情况。例如,逗号也将分隔单词,在下一个单词开始之前,它后面可能没有空格。不要从数组长度中减去一个:它确实具有单词的字符(仅),因此您需要全长。这些是使其正确的最小更改:function findLongestWordLength(str) {&nbsp; let arr = [];&nbsp; let longestWord = "";&nbsp; let longestNum = 0;&nbsp; str += " "; // trick to ensure that the last word is also inspected&nbsp; for (let i = 0; i <= str.length - 1; i++) {&nbsp; &nbsp; if (/\w/i.test(str[i])) { // match alphanumerical character, not anything.&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // The `i` suffix doesn't harm, but is useless here&nbsp; &nbsp; &nbsp; arr.push(str[i]);&nbsp; &nbsp; } else { // Remove any condition here.&nbsp; &nbsp; &nbsp; if (arr.length >= longestNum) { // you need the full length, not minus 1&nbsp; &nbsp; &nbsp; &nbsp; longestNum = arr.length;&nbsp; &nbsp; &nbsp; // (idem)&nbsp; &nbsp; &nbsp; &nbsp; longestWord = arr.join("");&nbsp; &nbsp; &nbsp; &nbsp; arr = [];&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; longestNum = longestNum; // not needed&nbsp; &nbsp; &nbsp; &nbsp; longestWord = longestWord; // not needed&nbsp; &nbsp; &nbsp; &nbsp; arr = [];&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; //console.log(arr);&nbsp; &nbsp; //console.log(longestWord);&nbsp; &nbsp; //console.log(longestNum);&nbsp; }&nbsp; return longestNum;}console.log(&nbsp; findLongestWordLength("The quick brown fox jumped over the lazy dog"))如您所知,有更短的方法可以做到这一点,例如使用这个函数式编程解决方案:function findLongestWordLength(str) {&nbsp; &nbsp; return Math.max(...str.match(/\w+|$/g).map(s => s.length));}console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript