IndexOf表示对象不存在,即使它应该存在

时间:2017-06-13 10:51:37

标签: javascript angularjs arrays object angular-material

我正在尝试获取数据库查询中项目的索引,但出于某种原因,我在尝试对数据使用indexOf时得到 -1 。 / p>

数据以md-select显示,并在一组对象(角色)上重复:

<div layout="row">
    <md-input-container>
        <label>Job Activity:</label>
        <md-select ng-model="activity" required>
            <md-option ng-repeat="activity in activities" ng-value="activity">
                {{ activity.Description }}
            </md-option>
        </md-select>
    </md-input-container>
</div>

显示作品绝对正常,但是当我提交上述md-select所在的表单时,我根本无法在活动/角色集合中找到所选活动的索引,即使它 COMES 来自该集合,不会发生任何操作。

以下是表单提交时发生的提交。角色是从role

中选择的md-select
vm.submitEmployment = function (role) {  
    console.log(role);
    console.log($scope.activities.indexOf($scope.role));
    console.log($scope.activities);

    $scope.data.role = role.Id;
    $scope.data.roleIndex = $scope.activities.indexOf($scope.role);
    $window.location.href = '#!/additionalInformation';
}

以上console.logs给我这个:

enter image description here

现在我不是火箭科学家,但这两个对象对我来说看起来完全一样。有什么我想念的吗?

4 个答案:

答案 0 :(得分:2)

稍微改变您的方法,使用Array.findIndex方法获取您想要的内容。如果使用lodash:

,lodash _.findIndex()会实现相同的功能
vm.submitEmployment = function (role) {

  // the idx variable should hold your index number
  var idx = $scope.activities.findIndex((item) => $scope.role.Id === item.Id);

}

答案 1 :(得分:0)

尝试映射您的数组以获取ID,然后搜索您的Id的索引:

$scope.activities.map(function(role) { 
   return role.Id;
}).indexOf(role.Id);

答案 2 :(得分:0)

  

indexOf()使用strict将searchElement与Array的元素进行比较   等式(与===或三等号运算符使用的方法相同)

var a = {a: 2}
var b = {a: 2}
a === b // false
  

原因是内部JavaScript实际上有两种不同的方法来测试相等性。字符串和数字等原语按其值进行比较,而数组,日期和普通对象等对象则按其引用进行比较。通过引用进行的比较基本上会检查给定的对象是否指向内存中的相同位置。

因此,如果您按id搜索,请尝试以下内容:

$scope.activities.map(function(a) { return a.id; }).indexOf($scope.role.id)

答案 3 :(得分:0)

如果您使用ES6很好,可以使用findIndex函数。所以,你可以这样做:

const index = $scope.activities.findIndex(item => item.id === role.id);