Switch 语句,它不适用于提示

Switch Statement, it does not work with prompt

我刚学了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) {
//...

输入表达式和case表达式之间的switch statement performs a strict comparison。以下输出将是:

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

提示函数returns一个字符串所以要么:

  • 将您的案例陈述更改为 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]");