简体   繁体   中英

Why does function return undefined?

So, I've recently started leaning how to code and I am trying to figure out how to create a function that will take a string and add the suffix 'ay' to the end if the conditions are met. For some reason, I keep getting 'undefined' whenever I run the function. I've tried rewriting it a few times but I keep getting something wrong and I can't figure out what it is! If someone can look this over and explain what I'm missing I would really appreciate it!

function translate(val) {
    let piggy = 'ay'
    let newVal = Array.from(val);
    let finalVal;
    let i = 0;
    while (i < newVal - 1) {
        if (newVal[0] == 'a' || newVal[0] == 'e' || newVal[0] == 'i' || newVal[0] == 'o' || newVal[0] == 'u') {
             finalVal = newVal.join('') + piggy;
             return finalVal;
        } else {
            finalVal = newVal;
            return finalVal;
        }
    i++
    } 
}
translate('apple')

At a glance, you're subtracting a number from an array. This returns NaN and doesn't even hit the while loop. ( x < NaN is always false)

Because you're not hitting the while loop the function just exists and never returns a value. That is why you receive undefined .

If you want to iterate over your newly created array, you'll want to use newVal.length .

Fixed code is as follows:

    let piggy = 'ay'
    let newVal = Array.from(val);
    let finalVal;
    let i = 0;
    while (i < newVal.length - 1) {
        if (newVal[0] == 'a' || newVal[0] == 'e' || newVal[0] == 'i' || newVal[0] == 'o' || newVal[0] == 'u') {
             finalVal = newVal.join('') + piggy;
             return finalVal;
        } else {
            finalVal = newVal;
            return finalVal;
        }
    i++
    } 
}
translate('apple')

You're missing a return statement, and I'm not sure what you are trying to do here... Are you trying to append 'ay' to the string, if it starts with a vowel?

if yes, this is a simplified version of your code :

function translate( val ) {
  if([ "a", "e", "i","o","u"].includes(val[0])) {
     return val + 'ay';
     }
   else return val;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM