2.6 KiB
2.6 KiB
id | title | challengeType | videoUrl | forumTopicId | dashedName |
---|---|---|---|---|---|
56533eb9ac21ba0edf2244e0 | 用一個 Switch 語句來替代多個 if else 語句 | 1 | https://scrimba.com/c/c3JE8fy | 18266 | replacing-if-else-chains-with-switch |
--description--
如果你有多個選項需要選擇,switch
語句寫起來會比多個串聯的 if
/else if
語句容易些。 譬如:
if (val === 1) {
answer = "a";
} else if (val === 2) {
answer = "b";
} else {
answer = "c";
}
可以被下面替代:
switch(val) {
case 1:
answer = "a";
break;
case 2:
answer = "b";
break;
default:
answer = "c";
}
--instructions--
把串聯的 if
/else if
語句改成 switch
語句。
--hints--
不要使用 else
表達式。
assert(!/else/g.test(code));
不要使用 if
表達式。
assert(!/if/g.test(code));
你應該有至少 4 個 break
表達式。
assert(code.match(/break/g).length >= 4);
chainToSwitch("bob")
應該是字符串 Marley
assert(chainToSwitch('bob') === 'Marley');
chainToSwitch(42)
應該是字符串 The Answer
assert(chainToSwitch(42) === 'The Answer');
chainToSwitch(1)
應該是字符串 There is no #1
assert(chainToSwitch(1) === 'There is no #1');
chainToSwitch(99)
應該爲 Missed me by this much!
。
assert(chainToSwitch(99) === 'Missed me by this much!');
chainToSwitch(7)
應該是字符串 Ate Nine
assert(chainToSwitch(7) === 'Ate Nine');
chainToSwitch("John")
應該爲 ""
(empty string)。
assert(chainToSwitch('John') === '');
chainToSwitch(156)
應該爲 ""
(empty string)。
assert(chainToSwitch(156) === '');
--seed--
--seed-contents--
function chainToSwitch(val) {
var answer = "";
// Only change code below this line
if (val === "bob") {
answer = "Marley";
} else if (val === 42) {
answer = "The Answer";
} else if (val === 1) {
answer = "There is no #1";
} else if (val === 99) {
answer = "Missed me by this much!";
} else if (val === 7) {
answer = "Ate Nine";
}
// Only change code above this line
return answer;
}
chainToSwitch(7);
--solutions--
function chainToSwitch(val) {
var answer = "";
switch(val) {
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
answer = "Ate Nine";
}
return answer;
}