Arrays 返回带有';正确';参数
我有一个Arrays 返回带有';正确';参数,arrays,angularjs,foreach,push,truthiness,Arrays,Angularjs,Foreach,Push,Truthiness,我有一个teamDetails数组,其中有一个band数组,其中有player对象。每个玩家对象都有一个属性,该属性包含值“true”或“false” 我想写一个函数,在数组中循环,只返回受伤属性值为true的玩家 这就是我目前所拥有的(不工作): 我看不出这有什么问题。如果有人可以,将非常感谢您的帮助。如果迭代在数组的数组中这是正确的实现: $scope.injuredPlayerSearch = function() { var injuredPlayers = []; $scop
teamDetails
数组,其中有一个band
数组,其中有player
对象。每个玩家对象都有一个属性,该属性包含值“true”
或“false”
我想写一个函数,在数组中循环,只返回受伤属性值为true的玩家
这就是我目前所拥有的(不工作):
我看不出这有什么问题。如果有人可以,将非常感谢您的帮助。如果迭代在数组的数组中
这是正确的实现:
$scope.injuredPlayerSearch = function() {
var injuredPlayers = [];
$scope.teamDetails.forEach(function(t){
t.squad.forEach(function(o) {
if (o[injured] === true) {
injuredPlayers.push(o)
}
});
});
return injuredPlayers;
}
您可以使用filter
返回受伤的球员:
$scope.injuredPlayerSearch = function() {
return $scope.teamDetails.squad.filter(function(o) {
return o[injured];
});
}
试试这个
var injuredPlayers = [];
angular.forEach($scope.teamDetails.squad,function(s){
if (s.injured === true) {
injuredPlayers.push(s)
}
})
return injuredPlayers;
使用javascript
您不需要编写任何函数。我在那里等你
var injuredPlayers = $filter('filter')($scope.teamDetails.squad, {injured:true}, true);
这里$filter是角度过滤器。不要将依赖注入到您正在使用的控制器或服务中
有关角度过滤器的详细信息,请参阅
注意:第二个true用于严格的类型检查。它相当于受伤===true
编辑
对于直接在视图上显示它,角度有更好的解决方案
{{teamDetails.squad | filter:{injured:true}:true}}
在视图中使用不需要任何依赖项注入或控制器。您做的一切都是正确的,只是留下了一些东西
$scope.injuredPlayerSearch = function() {
var injuredPlayers = [];
angular.forEach($scope.teamDetails.squad,function(o) {
if (o[injured] === true) {
injuredPlayers.push(o)
}
});
return injuredPlayers;
}
你们有实际数据的例子吗?好的,这看起来像我想要的。所以如果我把这个放在我的控制器里<代码>$scope.injuredPlayers=$filter($scope.teamDetails.squad,{injured:true},true),然后在我的视图中调用
{{campredplayers}}
,这样行吗?如果只需要在视图中显示,您可以在视图中直接使用它。更新答案。
{{teamDetails.squad | filter:{injured:true}:true}}
$scope.injuredPlayerSearch = function() {
var injuredPlayers = [];
angular.forEach($scope.teamDetails.squad,function(o) {
if (o[injured] === true) {
injuredPlayers.push(o)
}
});
return injuredPlayers;
}