使用 indexOf 查看 angularJS 中的对象是否匹配

using indexOf to see if there is a match in an object in angularJS

我想遍历一组应用程序编号,看看是否有使用 indexOf 的匹配项。

目前我的阵列看起来像..

数组:

"applications":[  
         "123456",
         "224515",
         "658454",
         "784123"
      ]

我的控制器:

$scope.hasApplicationNumber = function (appNo) {
        var applicationsArray = applications;
        return applicationsArray.indexOf(appNo);
      }

html:

<span ng-if="hasApplicationNumber(784123)">Its a Match!</span>

indexOf 方法 returns 匹配 numberindex。所以你应该检查它是否大于-1。在这里你正在检查 number 而不是 string(数组成员),所以在检查之前你必须将所有数组转换为数字并检查否则检查 appNostring 然后找到它在一个数组中。

$scope.hasApplicationNumber = function (appNo) {
    var applicationsArray = applications;
    //return applicationsArray.indexOf(appNo.toString()) > -1;
    //OR
    //return !!~applicationsArray.map(Number).indexOf(appNo); //then check number
    //OR
    return !!~applicationsArray.indexOf(appNo.toString());
}

我是不是误会了什么?为什么不直接使用 Array.prototype.includes?

免责声明:这使用 ES6 箭头语法,

$scope.hasApplicationNumber = function (appNo) {
    return applicationsArray.map(no => Number(no)).includes(appNo);
}

JS Fiddle Link: https://jsfiddle.net/3p4mq9qL/

编辑:如果您想按数字查看(当数组为字符串时)已修复

DEMO

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
    $scope.applications = [  
         "123456",
         "224515",
         "658454",
         "784123"
      ];

    $scope.hasApplicationNumber = function (appNo) {
        var res = $scope.applications.filter(item => { return item.indexOf(appNo) != -1; });
        return (res.length) ? true : false;
      }  
});

<div ng-app="myApp" ng-controller="MyCtrl">
  <span ng-if="hasApplicationNumber(784123)">Its a Match!</span>
</div>