gpt4 book ai didi

javascript - Switch 语句,它不适用于提示

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:13:54 24 4
gpt4 key购买 nike

我刚刚学习了 switch 语句。我正在通过构建一些东西来练习它。当我将变量的值设置为一个数字时它起作用但是当我要求用户输入一个数字时它总是输出默认语句

它适用于此代码:

confirm("You want to learn basic counting?");
var i = 0;
switch (i) {
case 0:
console.log(i);
i++
case 1:
console.log(i);
i++;
case 2:
console.log(i);
i++;
case 3:
console.log(i);
i++;
case 4:
console.log(i);
i++;
case 5:
console.log(i);
i++;
case 6:
console.log(i);
i++;
case 7:
console.log(i);
i++;
case 8:
console.log(i);
i++;
case 9:
console.log(i);
i++;
case 10:
console.log(i);
console.log("Congratulations!");
break;
default:
console.log("Buzz, wronghh");
break;
}

但是当我向用户询问值(value)时,它不起作用。下面的代码不起作用:

confirm("You want to learn basic counting?");
var i = prompt("Type any number from where you want to start counting[Between 0 and 10]");
switch (i) {
case 0:
console.log(i);
i++
case 1:
console.log(i);
i++;
case 2:
console.log(i);
i++;
case 3:
console.log(i);
i++;
case 4:
console.log(i);
i++;
case 5:
console.log(i);
i++;
case 6:
console.log(i);
i++;
case 7:
console.log(i);
i++;
case 8:
console.log(i);
i++;
case 9:
console.log(i);
i++;
case 10:
console.log(i);
console.log("Congratulations!");
break;
default:
console.log("Buzz, wronghh");
break;
}

最佳答案

您需要将用户输入从字符串转换为整数,就像这样

confirm("You want to learn basic counting?");
var i = prompt("Type any number from where you want to start counting[Between 0 and 10]");
i = parseInt(i); // this makes it an integer
switch(i) {
//...

关于javascript - Switch 语句,它不适用于提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31662389/

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