检查给定的 5 位数字中的所有 5 位数字是否相同

Check if all the 5 digits in a given 5 digit number are same

本文关键字:数字 是否 检查      更新时间:2023-09-26

如果给定的 5 位数字中的所有 5 位数字都相同,例如 11111、22222 等,我想显示警报。这是我的小提琴 http://jsfiddle.net/09k8f5s4/36/下面是我的代码不起作用。任何帮助将不胜感激。

<div ng-app="app" ng-controller="test">
      <input type="text" ng-model="value"/>
     <button ng-click=check()>Check</button>
 </div>
angular.module('app', [])
  .controller('test', function($scope) {
      $scope.check = function() {
          if(/('d)'1{2}-'1{3}-'1{4}/.test($scope.value)) {
            alert("Invalid number");      
          }
      }
});

你的意思是你知道正好有 5 个整数存在,所以我会针对 mod11111 进行测试。

Plain JavaScript。 假设number是一个字符串:

function isAllSameDigit(number){
    for(var i = 0; i < number.length; i++){
        if(number[0] != number[i])
            return false;
    }
    return true;
}

一旦发现差异,这将短路。

这是一个快速的香草版本(我对 Angular 不太熟悉):

var num = 44444;
var num2 = 44445;
function areSame(num) {
    var arr = String(num).split('');
    return arr.every(function (el) { return el === arr[0]; });
}
console.log(areSame(num));
console.log(areSame(num2));

您可以使用

以下正则表达式^([0-9])'1*$

angular.module('app', [])
  .controller('test', function($scope) {
      $scope.check = function() {
          if(/^([0-9])'1*$/.test($scope.value)) {
            alert("Invalid number");      
          }
      }
});

参见 JSFIDDLE

function check(input) {
  // convert input to string 
  input += "";
  // verify only 5 characters
  if (input.length !== 5) {
    throw new Error("Input is not 5 digits long.");
  }
  // verify it is numeric.
  if (!$.isNumeric(input)) {
    throw new Error("Input is not a numeric value.");
  }
  var allSame = true;
  var firstChar = input[0];
  // Loop through looking for something different
  for (var i = 0; i < 5; i++) {
    if (input[i] !== firstChar) {
      allSame = false;
      break;
    }
  }
  return allSame;
}

嘿,你的正则表达式不正确:-

使用:-/^''D*(''d)(?:''D*|''1)*$/.test($scope.value)

angular.module('app', [])
  .controller('test', function($scope) {
      $scope.check = function() {
          if(/^'D*('d)(?:'D*|'1)*$/.test($scope.value)) {
            alert("Invalid number");      
          }
      }
});

小提琴 :-http://jsfiddle.net/95ydag0b/