Switch语句,它不能与prompt一起工作

Switch Statement, it does not work with prompt

本文关键字:prompt 一起 工作 不能 语句 Switch      更新时间:2023-09-26

我刚学了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;
}

但是当我向用户请求值时,它不起作用。下面的代码不起作用:

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) {
//...

switch语句严格比较输入表达式和大小写表达式。下面的输出将是:

var i = 1;
switch (i) {
    case "1":
        console.log('String 1');
        break;
    case 1:
        console.log('Number 1');
        break;
}
// Number 1
var j = "1";
switch (j) {
    case "1":
        console.log('String 1');
        break;
    case 1:
        console.log('Number 1');
        break;
}
// String 1

提示函数返回一个字符串,因此:

  • 将您的case语句更改为case "1":, case "2":
  • 用户使用i = Number(i)
  • 输入数字

除了其他答案,您还可以使用一元加号。它实际上做了与Number(…)相同的事情,但更短。换句话说,加号运算符+应用于单个值,对数字没有任何作用。但如果操作数不是数字,则一元加号将其转换为数字。

例如:

let a = '2';
alert( a + 3); // 23

,

let a = '2';
alert( +a + 3); // 5

所以在代码中添加一元+前提示符:

var i = +prompt("Type any number from where you want to start counting[Between 0 and 10]");