切换语句,它不起作用提示

时间:2015-07-27 20:13:46

标签: javascript syntax switch-statement 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;
}

3 个答案:

答案 0 :(得分:7)

您需要将用户输入从字符串转换为整数,如此

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

答案 1 :(得分:2)

switch语句在输入表达式和case表达式之间执行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

提示函数返回一个字符串,所以:

  • 将您的个案陈述更改为case "1":case "2":
  • 使用i = Number(i)
  • 表示用户输入的数字

答案 2 :(得分:0)

我知道这个问题之前已经回答过了,但我想补充一些其他的东西。除了其他答案之外,您还可以使用一元加号 +。它实际上与 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]");