function getLetter(s) {
let letter = s[0];
// Write your code here
let A = ['a','e','i','o','u'];
let B = ['b','c','d','f','g'];
let C = ['h','j','k','l','m'];
let D = ['n','p','q','r','s','t','v','w','x','y','z'];
switch(letter) {
case A.includes(s.charAt(0)):
return 'A';
break;
case B.includes(s.charAt(0)):
return 'B';
break;
case C.includes(s.charAt(0)):
return 'C';
break;
case D.includes(s.charAt(0)):
return 'D';
break;
}
}
s = 'adam';
t = getLetter(s);
console.log(t);
I'm learning switches and I'm trying this problem where I'm supposed to pass in a string and the function getLetter() is supposed to return 'A' if the first letter of the string is any of the elements in array A. And similar for arrays B,C,D. I tried the code above but it returns undefined. What am I doing wrong?
You need to check against a boolean value, like true
, because you use includes
, which returns true
or false
.
BTW, by using return
in each case
, you could omit to break
, because the function exits with return
, which exits the switch
statement as well.
function getLetter(s) { let letter = s[0]; // Write your code here let A = ['a', 'e', 'i', 'o', 'u']; let B = ['b', 'c', 'd', 'f', 'g']; let C = ['h', 'j', 'k', 'l', 'm']; let D = ['n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']; switch (true) { // <-- boolean value with strict comparison === case A.includes(letter): return 'A'; case B.includes(letter): return 'B'; case C.includes(letter): return 'C'; case D.includes(letter): return 'D'; } } var s = 'adam', t = getLetter(s); console.log(t);
You can use find
instead of includes
, when you pass a character to switch()
it tries to match that against case, since includes
return true/false
so it won't match any case
function getLetter(s) { let letter = s[0]; let A = ['a', 'e', 'i', 'o', 'u']; let B = ['b', 'c', 'd', 'f', 'g']; let C = ['h', 'j', 'k', 'l', 'm']; let D = ['n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']; switch (letter) { case A.find(v => v === letter): return 'A'; case B.find(v => v === letter): return 'B'; case C.find(v => v === letter): return 'C'; case D.find(v => v === letter): return 'D'; } } s = 'adam'; t = getLetter(s); console.log(t);
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.