这是我过滤掉记录的代码
for (var k = 0; k < $scope.hockeyPlayersId.length; k++) {
var val = $scope.hockeyPlayersId[k];
$scope.filterhockeyPlayers = $scope.Players.filter(function (obj, index) {
var returnVal = true;
if (val) {
if (obj.PlayersId == val)
return 1
else
return 0;
}
return returnVal;
});//End of filter function ;
}
val包含玩曲棍球的所有玩家的ID。我将obj的每个PlayersId
与val进行比较,但$scope.filterhockeyPlayers
返回错误的值,如果$scope.hockeyPlayersId = ['22','12','21']
则返回仅包含21个id的玩家。我也想要22和12的球员。每个for循环后都会丢失$scope.filterhockeyPlayers
值。
答案 0 :(得分:1)
您的代码存在一些问题:
$scope.filterhockeyPlayers
循环的每次迭代时都覆盖for
,因此只会使用$scope.hockeyPlayersId
的最后一项的结果,其余部分将被省略。returnVal
完全没用。由于1
。0
或if-else
醇>
现在,要解决此问题,您必须更改代码,以便filter
位于最外层。对于$scope.Players
中的每个对象,只需使用$scope.hockeyPlayersId
或Array#indexOf
检查该对象的ID是否包含在Array#includes
中:
$scope.filterhockeyPlayers = $scope.Players.filter(function (obj) { // filter objects from $scope.Players
return $scope.hockeyPlayersId.includes(obj.PlayersId); // where the id is included in $scope.hockeyPlayersId
});
这与使用for
循环相同:
$scope.filterhockeyPlayers = $scope.Players.filter(function (obj) {
for (var k = 0; k < $scope.hockeyPlayersId.length; k++) {
if(obj.PlayersId == $scope.hockeyPlayersId[k]) {
return true;
}
}
return false;
});
我希望它有意义; - )