gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:57:13 26 4
gpt4 key购买 nike

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

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

编辑:这是我实际测试代码是否有效的 freeCodeCamp 练习:https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string由于某种原因,大多数答案都可以在此处的代码片段中使用,但不能在 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");

最佳答案

我假设使用 /./i.test(str[i]) 您试图匹配除空格之外的所有内容。 . 匹配除换行符之外的所有内容,因此我将其切换为 [^\s] 它实际上匹配除空格之外的所有内容。我还将控制台日志放在循环之外,因此输出在某种程度上是可读的。

function findLongestWordLength(str) {

let arr = [];
let longestWord = "";
let longestNum = 0;

for (let i = 0; i <= str.length - 1; i++) {
if (/[^\s]/i.test(str[i])) {
arr.push(str[i]);
} else if (/[\s]/i.test(str[i])) {
if (arr.length > longestNum) {
longestNum = arr.length;
longestWord = arr.join("");
arr = [];
} else {
longestNum = longestNum;
longestWord = longestWord;
arr = [];
}
}

}
console.log(arr); // last word since you reset arr every step
console.log(longestWord);
console.log(longestNum);
return longestNum;
}

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

更好的方法是:

function findLongestWordLength(sentence) {
const words = sentence.split(' ');
return words.reduce((max, currentWord) => max > currentWord.length ? max : currentWord.length, 0);
}

关于javascript - 使用此代码在 JS 中查找字符串中最长的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58791089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com