0
How this code returns maximum length of a string?
According to me it should return length of last word in a string(in the given example i.e, 7) ? Where I went wrong?Anybody clarify me https://code.sololearn.com/Wp33Vd4YLp30/?ref=app
8 Antworten
+ 2
Martin Taylor Sry,I'm newbie ..But trying to understand...
I know 8 is longer than 7 but I still thinking how this code inside the for loop returns 8 , I tried to understand but
when i=0,it returns 4,
i=1, //2
i=2,//3
i=3,//7
i=4,//8
.
.
i=9,//7
As far as I understood, irrespective of the longestword, it returns length of last word of the string.since I iterates till 9(index of last word)
Which condition makes the function so it returns 8 ?
+ 1
Now I understood.,why did I make it complex 😬😂.,thank you 🙌
0
Martin Taylor function longestWord(str){
var words=str.split(' ');
var maxLength=0;
for(var i=0;i<words.length;i++){
if(words[i].length>maxLength){
maxLength=words[i].length;/*returns first word , i increments to 1,returns 2nd word.so on*/
}
}
console.log(maxLength);
}
longestWord("What is the average airspeed velocity of an unladen swallow");
0
Martin Taylor where I went wrong ..?
https://code.sololearn.com/W7AH0z9oGqqj/?ref=app