与提示函数结合使用时,switch 语句始终执行 default case

我在 HTML 中编写了以下 switch 语句:


<script>

    const day = prompt("Enter day number: ");

    switch (day) {

        case 1:

            document.write("Sun");

            break;

        case 2:

            document.write("Mon");

            break;

        case 3:

            document.write("Tue");

            break;

        default:

            document.write("Wrong Choice");

    }

</script>

Wrong Choice即使我通过1或2


Smart猫小萌
浏览 83回答 2
2回答

斯蒂芬大帝

prompt总是返回一个string,并且 case 与===- 字符串不会===与数字进行比较。将您的 case 改为字符串:const day = prompt("Enter day number: ");switch (day) {&nbsp; case '1':&nbsp; &nbsp; document.write("Sun");&nbsp; &nbsp; break;&nbsp; case '2':&nbsp; &nbsp; document.write("Mon");&nbsp; &nbsp; break;&nbsp; case '3':&nbsp; &nbsp; document.write("Tue");&nbsp; &nbsp; break;&nbsp; default:&nbsp; &nbsp; document.write("Wrong Choice");}但switch相当冗长并且容易出错。考虑使用对象或数组代替:const days = [, 'Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];const dayNum = prompt("Enter day number: ");const day = days[dayNum] || 'Invalid';console.log(day);

蝴蝶刀刀

我猜它是作为字符串传递的。试着做&nbsp; &nbsp;<script>const day = prompt("Enter day number: ");switch (day) {&nbsp; &nbsp; case ‘1’:&nbsp; &nbsp; &nbsp; &nbsp; document.write("Sun");&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case ‘2’:&nbsp; &nbsp; &nbsp; &nbsp; document.write("Mon");&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case ‘3’&nbsp; &nbsp; &nbsp; &nbsp; document.write("Tue");&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; document.write("Wrong Choice");}</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5