javascript - For loop is stopping at the first letter in string? -
this rovarspraket function. loop not iterating on other letters in phrase. stops @ 't' first letter in string. function returning 'tot' instead of full string of 'tothohisos isos fofunon'. i've been staring @ long. suggestions help. i'm novice javascript way.
function translate (phrase) { var splitphrase = phrase.split().join(); var letter = splitphrase[i]; var vowels = ['a', 'e', 'i', 'o', 'u']; var output = ''; (i = 0; < phrase.length; i++) { if(vowels.indexof(letter) === -1) { output = letter + 'o' + letter; } else { } return output } }; undefined translate('this fun') "tot"
there handful of mistakes or things may have overlooked in order reach final desired result of "tothohisos isos fofunon":
- you aren't appending data
output
, you're overwriting it. - you
return
within loop, stopping loop after first letter - you using index
i
before exists. - unnecessary splitting , joining
- not handling case of when letter is vowel
- not handling spaces
here's corrected version:
function translate (phrase) { var vowels = ['a', 'e', 'i', 'o', 'u', ' ']; // handle spaces var output = ''; (var = 0; < phrase.length; i++) { // use var declare index variable var letter = phrase[i]; // array notation accesses character in position if (vowels.indexof(letter) === -1) { output += letter + 'o' + letter; // += appends } else { output += letter; // handle vowels & spaces } } return output; // return outside loop }; alert(translate('this fun'));
Comments
Post a Comment