检查数组中是否存在新创建的对象(特定于AngularJS)

时间:2014-11-05 18:22:29

标签: javascript arrays angularjs

每次选中/取消选中复选框时,都会调用toggleIntervention函数。它应该将一个对象推送到数组或从数组中删除它,具体取决于它是否已选中/未选中。

我正在使用indexOf来检查对象是否存在于数组中,但是即使对象存在于数组中,索引始终为-1。我错过了什么?

    $scope.selectedInterventions=[];
    $scope.toggleIntervention = function(inputIntervention) {

        var intervention =  {
                cptCode:inputIntervention.service,
            description:inputIntervention.description,
                  notes:"intervention notes",
             targetDate:"11/11/2014",
         resolutionDate:"11/11/2014"
        };

        // The index always -1 even if the object exists in the array of selectedInterventions
        var idx = $scope.selectedInterventions.indexOf(intervention); 
        if (idx > -1) { 
            $scope.selectedInterventions.splice(idx, 1);
        } else {
            $scope.selectedInterventions.push(intervention);
        }
    };

0 个答案:

没有答案