我的代码出现错误
这是代码
function findLongestWordLength(str) {
let word = str.split(" ");
console.log(word);
let totalWords = word.length;
for (let i = 0; i <= totalWords; i++) {
let max = '';
let cmax = word[i].length;
console.log(cmax);
if (cmax > max) {
max = cmax;
}
}
console.log(max);
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
我很困惑,因为它在控制台中显示 cmax
但之后出现错误。
最佳答案
正如已经提到的,您循环得太远,需要将最大值移到循环之外。
此外,请返回该值,而不是将其记录在函数中的控制台
这是一个更简洁的版本 - 请注意,这里没有太多输入控制
const findLongestWordLength = str => str && str
.match(/\w+/g) // find all words without spaces and punctuation
.sort((a,b) => a.length - b.length) // sort ascending on length
.pop() // pop the last word
.length; // return its length
console.log(
findLongestWordLength("The quick brown fox jumped over the lazy dog")
);
console.log(
findLongestWordLength("fox")
)
console.log(
findLongestWordLength("") // not handled
)
关于javascript - 在javascript中查找字符串中最长的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75642121/