AngularJS中的空值错误

时间:2014-04-07 12:06:34

标签: angularjs

我按照地点名称计算我有多少库存。一切正常,但如果location name = null我的控制台出现错误Cannot read property 'name' of null

$scope.stored = function(name) {
        $scope.count = 0;
        for(var i = 0; i < $scope.inventories.length; i++){
            if($scope.inventories[i].location.name == name){
                $scope.count = $scope.count + 1;
            } 
        }
            return $scope.count;
        };

1 个答案:

答案 0 :(得分:2)

我正在从评论中提取答案并在此发布给未来的访问者:

您需要将if($scope.inventories[i].location.name == name){更改为if($scope.inventories[i].location && $scope.inventories[i].location.name == name){