Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  47] [ 1]  / answers: 1 / hits: 73956  / 11 Years ago, sun, june 30, 2013, 12:00:00
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.


More From » javascript

 Answers
9

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++)

[#77302] Friday, June 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;