JS魔法八球实现中switch仅执行default分支,求问题排查
魔法八球代码始终走default分支的问题解决
问题出在类型不匹配:
Math.floor(Math.random() * 8)返回的是数字类型(0到7之间的整数)- 你switch里的case写的是字符串类型(比如
'0'、'1')
JS的switch判断用的是严格相等===,数字和字符串永远不会相等,所以所有case都匹配失败,只能走到default分支。
修正方法很简单,把case里的字符串换成数字就行,另外注意case 2后面的break漏了分号,顺手补上更规范:
let randomNumber = Math.floor(Math.random() * 8) let eightball = ''; switch (randomNumber){ case 0 : eightball = 'It is certain'; break; case 1 : eightball = 'It is decidedly so'; break; case 2 : eightball = 'Reply is hazy try again'; // 顺便修正拼写错误:Repy → Reply break; case 3 : eightball = 'Cannot predict now'; break; case 4 : eightball = 'Do not count on it'; break; case 5 : eightball = 'My sources say no'; break; case 6 : eightball = 'Outlook not so good'; break; case 7 : eightball = 'Signs point to yes'; break; default : eightball = 'yes'; break; } console.log(`The magic eightball said : ${eightball}.`);
运行这段代码就能正常匹配到各个分支了。
内容的提问来源于stack exchange,提问作者Nikcross
相关产品推荐
相关产品推荐

