我正在构建一个普通的 JS 计算器,并尝试使用正则表达式 .test() 函数来限制用户连续多次使用运算符
i.e. 2++++3
它的结构为 if else 语句,问题是正则表达式测试第一次有效,但第二次失败,从而导致代码在不应该的情况下跳转到 else 语句。我的正则表达式错误吗?我是否使用了错误的函数来运行比较?
var testOperands = /[+-/*=]/g;
switch (x) {
case "+":
if(testOperands.test(currentEntry[0])){
currentArea.textcontent = x;
totalArea.textContent = totalArea.textContent + "";
} else {
currentArea.textContent = x;
totalArea.textContent = (totalArea.textContent + x);
currentEntry = ["+"];
totalEntry.push(x);
}
break;
case "-":
if(currentEntry[0] === "-"){
currentArea.textcontent = x;
} else {
currentArea.textContent = x;
totalArea.textContent = (totalArea.textContent + x);
currentEntry = ["-"];
totalEntry.push(x);
}
break;
最佳答案
您的正则表达式无效,-
需要转义:[+\-\/*=]
关于javascript - 为什么 .test() 函数对于 onclick 行为不可靠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48708300/