我是js /编程的新手,只是使用提示创建一个简单的计算器。我试图验证输入的是数字而不是字符串。我试过这个
var operatorType = prompt("Do you want to add, subtract, multiply or divide?").toLowerCase();
switch (operatorType) {
case 'add':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
if (isNaN(i) === false) && (isNaN(j) === false) {
document.write(i+" plus "+j+" equals "+(i+j));
} else {
document.write("You didn't enter two numbers.");
}
break;
和if (i != 'string') && (j != 'string')
一样,但我一直得到"意想不到的令牌&&"。我查了一下,如果/在一个案例中是有效的,那么我不确定我做错了什么。
完整代码,如果有帮助
var operatorType = prompt("Do you want to add, subtract, multiply or divide?").toLowerCase();
switch (operatorType) {
case 'add':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
if (isNaN(i) === false) && (isNaN(j) === false) {
document.write(i+" plus "+j+" equals "+(i+j));
} else {
document.write("You didn't enter two numbers.");
}
break;
case 'subtract':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
document.write(i+" minus "+j+" equals "+(i-j));
break;
case 'multiply':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
document.write(i+" multiplied by "+j+" equals "+(i*j));
break;
case 'divide':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
document.write(i+" divided by "+j+" equals "+(i/j));
break;
default:
document.write("Please enter whether you want to add, subtract, multiply or divide.");
break;
}
答案 0 :(得分:0)
您的括号位于错误的位置导致语法错误。您需要移动此行中的括号以更改:
if (isNaN(i) === false) && (isNaN(j) === false) {
这样就变成了:
if (isNaN(i) === false && (isNaN(j) === false)) {
您还需要将字符串转换为数字,以便您的代码真正添加/ etc而不是连接文本。