Javascript:在字符串中查找最长的单词 [英] Javascript: find longest word in a string
本文介绍了Javascript:在字符串中查找最长的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
当我致电 longestWord(傲慢与偏见) )
,它返回'Pride'而不是'Prejudice',这是最长的单词......为什么?我检查了一些其他类似的问题,但解决方案看起来很像我的代码。
When I call longestWord("Pride and Prejudice")
, it returns 'Pride' and not 'Prejudice' which is the longest word... why? I checked some other similar questions, but the solutions looked a lot like my code.
推荐答案
那是因为你没有比较所有数组中的项目,你省略了最后一项。
That's because you're not comparing all the items in the array, you leave out the last one.
for (var i = 0; i < str.length - 1; i++)
应该是
for (var i = 0; i < str.length; i++)
或
for (var i = 0; i <= str.length - 1; i++)
这篇关于Javascript:在字符串中查找最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文