function myFunction2() {
var booloo = document.getElementById('texa').value;
if (!document.getElementById('texa').value) {
//var res = booloo.lastcharAt(booloo.value);
console.log("nothing");
} else if (booloo.substring(booloo.length - 1) == "+" || "-" || "*" || "/") {
console.log("String Contain Operator at last");
} else if (booloo.substring(booloo.length - 1) == "0" || "1" || "2" || "3" || "4" || "5" || "6" || "7" || "8" || "9") {
console.log("String contain Operand at last");
}
}
<html>
<body>
<input types="text" id="texa">
<button onclick="myFunction2()">Try it</button>
</body>
</html>
我试图在我的代码中使用多个 if else block ,但在第三个 block (“最后一个字符串包含操作数”)这不起作用,只有剩下的两个 block 工作完美。我的目标是,如果用户键入值,例如 10+ 值,那么它将进入运算符最后包含的第二个 block 。如果假设用户键入 10+2,那么它必须进入第三个 block ,例如(“最后包含操作数”),但问题是它不会进入第三个 block 。
最佳答案
这不是比较的方式。
if(booloo.substring(booloo.length - 1) == "+" || "-" || "*" || "/")
应该写成
if(booloo.substring(booloo.length - 1) == "+"
|| booloo.substring(booloo.length - 1) == "-"
|| booloo.substring(booloo.length - 1) == "*"
|| booloo.substring(booloo.length - 1) == "/")
您现有的代码将像这样计算:
- 检查是否 booloo.substring(booloo.length - 1) == "+"
- 检查是否为“-”(总是 evals 为 true,语句的其余部分不会被测试,但我还是写出来了)
- 检查是否“*”(也总是评估为真)
- 检查是否“/”(也总是评估为真)
关于javascript - 为什么我的 multiple if else 在 JavaScript 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42948819/