简体   繁体   中英

I need to use switch statment to return a word from the set of words

Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (ie, a through z). It must return A, B, C, or D depending on the following criteria:

If the first character in string is in the set, then return A. If the first character in string is in the set, then return B. If the first character in string is in the set, then return C. If the first character in string is in the set, then return D. Hint: You can get the letter at some index in using the syntax s[i] or s.charAt(i).

function getLetter(s) {
    let letter;
    //letter=s.charAt(0)
    const set1= new Set(['a','e','i','o','u']);
    const set2=new Set(['b','c','d','f','g']);
    const set3=new Set(['h','j','k','l','m']);
    const set4=new Set(['n','p','q','r','s','t','v','w','x','y','z']);
    // Write your code here
    switch(s.charAt(0)){
        
        case 1:
        if(set1.has(s.charAt(0)))
        letter=A;
        break;
        
        case 2:
        if(set2.has(s.charAt(0)))
        letter=B;
        break;
        
        case 3:
        if(set3.has(s.charAt(0)))
        letter=C;
        break;
        
        case 4:
        if(set4.has(s.charAt(0)))
        letter=D;
        break;
    }
    return letter;
}

Wanted to know what is wrong in this code, I am getting undefined in the result.

You could check against the set with a boolean value.

 function getLetter(s) { let letter; const set1 = new Set(['a', 'e', 'i', 'o', 'u']); const set2 = new Set(['b', 'c', 'd', 'f', 'g']); const set3 = new Set(['h', 'j', 'k', 'l', 'm']); const set4 = new Set(['n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']); // Write your code here switch (true) { case set1.has(s[0]): letter = 'A'; break; case set2.has(s[0]): letter = 'B'; break; case set3.has(s[0]): letter = 'C'; break; case set4.has(s[0]): letter = 'D'; break; } return letter; } console.log(getLetter('e')); console.log(getLetter('b')); console.log(getLetter('k')); console.log(getLetter('s'));

You want a function to check the string. but in all switch cases, you are trying to check what? switch(s.charAt(0)) this will be evaluated, s.charAt will never can be a number without casting. So suggestions make always a default case (which will work always) and case

switch (true) {
case set1.has(s.charAt(0)):
  return 'A'

case set2.has(s.charAt(0)):
  return 'B'

case set3.has(s.charAt(0)):
  return 'C'

case set4.has(s.charAt(0)):
  return 'D'
default:
  return 0

}

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