javascript - 为什么 .test() 函数对于 onclick 行为不可靠?

标签 javascript regex

我正在构建一个普通的 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;

这是完整的代码:https://codepen.io/brianofblades/pen/KQWVYN

最佳答案

您的正则表达式无效,-需要转义:[+\-\/*=]

关于javascript - 为什么 .test() 函数对于 onclick 行为不可靠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48708300/

相关文章:

php - 使用 mod_rewrite 删除 .php 扩展并同时清理 GET url

java - 从字符串中删除重音

javascript - 如何在firebase云函数中添加时间戳

javascript - 向下移动一个 div ala Apple

javascript - 选择选择菜单中的第一个动态元素

c# regex : get all uri's, 但不是来自特定域

regex - 使用正则表达式与 p :keyFilter

java - 允许某些特殊字符的正则表达式模式

javascript - 如何水平对齐两个 React 组件?

javascript - Angular ng-options 复杂的 json 数组