Javascript:在字符串中找到最长的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17386774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: find longest word in a string
提问by bard
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;
}
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.
当我打电话时longestWord("Pride and Prejudice")
,它返回“傲慢”而不是“偏见”,这是最长的词......为什么?我检查了一些其他类似的问题,但解决方案看起来很像我的代码。
回答by Musa
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++)
should be
应该
for (var i = 0; i < str.length; i++)
or
或者
for (var i = 0; i <= str.length - 1; i++)
回答by merv
One advantage to taking a functional approach to such problems is that you don't even have to keep count
对此类问题采用函数式方法的一个优点是,您甚至不必计算
See MDN Array.reducefor more info. (note: reduce
needs shim for IE8)
有关更多信息,请参阅MDN Array.reduce。(注意:reduce
IE8 需要垫片)
function longer(champ, contender) {
return (contender.length > champ.length) ? contender : champ;
}
function longestWord(str) {
var words = str.split(' ');
return words.reduce(longer);
}
console.log(longestWord("The quick brown fox jumped over the lazy dogs"));
回答by aaronman
Here this is your solution with a forEach, this will help you avoid the error in the future
这是您使用 forEach 的解决方案,这将帮助您避免将来出现错误
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
console.log(longestWord("pride and prejudice"));
Your original problem was just the str.length - 1
should have just been str.length
, originally you wouldn't have gotten to the last element of the array
你原来的问题只是str.length - 1
本来应该是str.length
,原来你不会得到数组的最后一个元素
回答by tymeJV
You have a -1
in your condition, it never even scans it:
你的情况有一个-1
,它甚至从不扫描它:
for (var i = 0; i < str.length - 1; i++) {
Should be:
应该:
for (var i = 0; i < str.length; i++) {
回答by acdcjunior
The index is going up to str.length -1
:
指数上升至str.length -1
:
for (var i = 0; i < str.length - 1; i++) {
So the last word is not processed.
所以最后一个字没有被处理。
Try with: longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice")
. You'll see it works (returns AAAAAAAAAAAAAAAAAAAAAAAAA
).
尝试:longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice")
。你会看到它起作用(返回AAAAAAAAAAAAAAAAAAAAAAAAA
)。
In case you're in doubt, the simplest way to fix it is removing the -1
from the for
loop.
如果您有疑问,修复它的最简单方法是-1
从for
循环中删除。
for (var i = 0; i < str.length; i++) {
Check a demo with both versions (the problematic and the fixed): link here.
检查两个版本(有问题的和已修复的)的演示:链接在这里。
回答by Gergo Erdosi
回答by Shushanth Pallegar
ForEach is faster in FF but slower in Chrome, but for loop with the cached length and function apply/call is quite faster in both FF and chrome.
ForEach 在 FF 中更快,但在 Chrome 中更慢,但是具有缓存长度和函数应用/调用的 for 循环在 FF 和 chrome 中都更快。
Hope the below code helps:
希望下面的代码有帮助:
function getLongest (arrStr) {
var longest = 0, word;
for(var i=0 , len = arrStr.length ; i < len ; i++){
if(longest < arrStr[i].length) {
longest = arrStr[i].length;
word = arrStr[i];
}
}
return word;
}
function isLongest (str) {
var arrayStr = str.split(' ');
return function(fn) {
return fn.apply(this,[arrayStr]);
}
}
isLongest("hello aaaaaaaaaaaaaaaaaaaaaaaaa bbb")(getLongest); //aaaaaaaaaaaaaaaaaaaaaaaaa
回答by Shushanth Pallegar
does this solve the problem??
这能解决问题吗??
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;
}
document.write(longestWord("pride and prejudice"));
回答by Bekzat
function longestWord(sentence){
var arr = sentence.match(/[a-z]+/gi);
arr.sort(function(a, b){
return b.length - a.length;
});
return arr[0];
}
longestWord('hello man@#$%');
// ==> output: hello
回答by Cheyenne Crawford
I find that the .map method here helps a lot (this is if you want the character count of the word, not the word itself):
我发现这里的 .map 方法有很大帮助(这是如果您想要单词的字符数,而不是单词本身):
function findLongestWord(str) {
var array = str.split(/\s+/);
var wordLength = array.map(function(i) {
return i.length;
});
var largest = Math.max.apply(Math, wordLength);
return largest;
}