Javascript Switch语句,它不适用于提示符
我刚学会了switch语句。我通过建造一些东西来练习。当我将变量的值设置为一个数字时,它会工作,但当我要求用户输入一个数字时,它总是输出默认语句 它适用于以下代码:Javascript Switch语句,它不适用于提示符,javascript,syntax,switch-statement,prompt,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++;
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) {
//...
该语句在输入表达式和大小写表达式之间执行转换。以下内容的输出为:
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
prompt函数返回一个字符串,以便:
- 将案例陈述更改为
,案例“1”:
案例“2”:
- 使用
i=number(i)