Compare two last character in a string

前端 未结 2 1238
自闭症患者
自闭症患者 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:15

    You are very close. The problem is that you are adding the operator to the expression before you have checked if it is valid or not. It is better to check the last character of the existing expression and the new character as a separate variable.

    You also want to check if the length of expression is greater than 0 rather than 3 as otherwise, the user could enter two '+' characters straight away when the length is less than 3.

    var app = angular.module("myApp", []);
    
    app.controller("myCtrl", function ($scope) {
    
      $scope.expression = "";
    
      var liste = ['+', '/', '*'];
    
      $scope.add = function (ope) {
    
        // don't add to expression, just store into der
        var der = String(ope);
        var avantDer = $scope.expression[$scope.expression.length - 1];
    
        if ($scope.expression.length > 0 && liste.includes(der) && liste.includes(avantDer)) {
            alert("error");
        } else {
            $scope.expression += der;
        }
      };
    });
    
    
    {{expression}}

提交回复
热议问题