gpt4 book ai didi

javascript - 返回未定义的 Switch 语句

转载 作者:行者123 更新时间:2023-11-29 17:34:28 24 4
gpt4 key购买 nike

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);

我正在学习开关,我正在尝试这个问题,我应该传入一个字符串,如果字符串的第一个字母是任何元素,函数 getLetter() 应该返回 'A'在数组 A 中。数组 B、C、D 也类似。我试过上面的代码,但它返回未定义。我做错了什么?

最佳答案

您需要检查 bool 值,例如 true ,因为你使用 includes ,返回 truefalse .

顺便说一句,通过使用 return在每个case , 你可以省略 break ,因为函数以 return 退出, 退出 switch statement

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);

关于javascript - 返回未定义的 Switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58466366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com