javascript - Else statement not working -
i trying return longest word in array using foreach loop , return "00" when there no word. able part of returning longest word work correctly, when introduce else statement doesn't work anymore:
function findlongestword(input) { var arrwords = input.split(' '); var wordlength = 0; var word = ''; arrwords.foreach(function(wrd) { if (wordlength < wrd.length && wrd.length % 2 == 0) { wordlength = wrd.length; word = wrd; } else { return "00"; } }); return word; }
your return "00"
statement returns inner function , not findlongestword(input)
function.
you can initialize word "00". return "00" if not set inside foreach.
function findlongestword(input) { var arrwords = input.split(' '); var wordlength = 0; var word = '00'; arrwords.foreach(function(wrd) { if (wordlength < wrd.length && wrd.length % 2 == 0) { wordlength = wrd.length; word = wrd; } }); return word; }
Comments
Post a Comment