Compare two last character in a string

前端 未结 2 1239
自闭症患者
自闭症患者 2021-01-21 12:52

I am programming a calculator in AngularJS. I am stuck on a validating user input. I do not want the user to be able to enter two 2 operators (\'+\',\'/\',\'*\') next to each ot

2条回答
  •  感动是毒
    2021-01-21 13:26

    There were two things wrong.

    1. $scope.expression.length > 3 should have been $scope.expression.length > 2
    2. You were calling $scope.expression += String(ope); twice

    I made a minor change below so I could run it in the code snippet window.

    I also added subtraction to liste.

    var $scope = {
      expression: ""
    };
    
    
    var liste = ['+', '/', '*', '-'];
    
    debugger
    $scope.add = function (ope) {
      var temp = $scope.expression + String(ope);
      console.log(temp);
      var len = temp.length - 1;
    
      if (len > 1) {
        var der = temp[len];
        var avantDer = temp[len - 1];
    
        if (liste.includes(der) && liste.includes(avantDer)) {
          console.log("error");
        } else {
          $scope.expression = temp;
        }
      }
      else {
        $scope.expression = temp;
      }
    };
    
    $scope.add('3');
    $scope.add('+');
    $scope.add('-');

    When I call $scope.add('-'); it displays the error like you expect.

提交回复
热议问题