请让我知道这段代码有什么问题:
我知道有更简单的方法可以实现预期的结果,但是我想了解如何运行此特定代码,以及我的错误是什么。尝试尽可能少地改变它,否则让我知道为什么这行不通。另请注意,我正在尝试使用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");
小怪兽爱吃肉
ibeautiful
开满天机
相关分类