javascript - Comparing array elements to character -
i'm trying write simple javascript program check if letter vowel. problem output incorrect , should " vowel."
javascript:
function findvowel(letter1, vowels) { var count = vowels.length; (var = 0; < count; i++) { if (vowels[i] === letter1) { var message1 = " vowel"; document.getelementbyid('exercise3').innerhtml = letter1 + message1; } else { var message2 = " consonant"; document.getelementbyid('exercise3').innerhtml = letter1 + message2; } } }
html:
<script> $(document).ready(function() { findvowel("a",["a","e","i","o","u"]); }); </script>
output:
a consonant
add break
loop doesn't keep going.
function findvowel(letter1, vowels) { var count = vowels.length; (var = 0; < count; i++) { if (vowels[i] === letter1) { var message1 = " vowel"; document.getelementbyid('exercise3').innerhtml = letter1 + message1; break; } else { var message2 = " consonant"; document.getelementbyid('exercise3').innerhtml = letter1 + message2; } } }
you can use return false;
stop function right away when vowel matched, in normal cases break
used because there might other codes going on after loop.
btw:
function findvowel(letter){ //thanks p.s.w.g reminding me [] return letter+" "+(/[aeiou]/i.test(letter)?"vowel":"constant"); }
Comments
Post a Comment