Switch语句,它不能与prompt一起工作
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) {
//...
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]");
相关文章:
- 转义符不能与innerHTML一起使用
- 高亮显示与数组字符串一起使用时文本插件中断
- setTimeout可以与闭包内的函数一起使用吗
- 将依赖外部库的UMD模块与browserfy捆绑在一起
- Highcharts colorsByPoint与系列中的线性渐变一起使用时不起作用
- 如何将js库与typescript一起使用
- 将webpack和babel与父项目目录中的文件一起使用
- 将 Drag&Drop 与 jsTree 和 DataTables 一起使用
- Javascript-如何让脚本与Ajax请求的数据一起运行
- 将两个ext.TabPanels滚动到一起
- 使用prompt时反转数组
- 将jQuery UI Timepicker Addon与React一起使用
- 什么是curl以及如何将其与nodejs一起使用
- Javascript”;onmousemove”;事件无法与类一起使用
- 将require('..')与变量一起使用与在webpack中使用字符串相比
- 如何在php中创建一个函数,该函数与文本区域一起工作,通过输入类似[color:red]的内容来打印具有等效颜色的文本
- 三角库可以与firefox一起使用,但不能在Chrome中使用
- 为什么不't我的ruby代码与javascript文件一起插入
- 通过jQueryAjax一起发布Array和Form数据时出现问题
- Switch语句,它不能与prompt一起工作