【发布时间】:2016-05-26 18:38:11
【问题描述】:
我有一个玩家数组,每个玩家都是一个具有多个属性的对象,其中一个是“目标”。
var players = [
{
"id":"4634",
"name":"A. Turan",
"number":"0",
"age":"28",
"position":"M",
"goals":"1"
},
{
"id":"155410",
"name":"H. Çalhano?lu",
"number":"0",
"age":"21",
"position":"A",
"goals":"0"
},
{
"id":"4788",
"name":"B. Y?lmaz",
"number":"0",
"age":"30",
"position":"A",
"goals":"2",
}
]
我编写了一个函数来循环遍历数组并将每个目标超过“0”的元素推送到数组topScorers。像这样:
$scope.topScorerSearch = function() {
var topScorers = [];
$scope.teamDetails.squad.forEach(function(o) {
if (o.goals > 0) {
topScorers.push(o)
}
});
return topScorers;
}
函数名为{{topScorerSearch()}}。
这只会返回得分的球员。完美。
但是,我想在其他属性上运行这个,这会导致很多重复的代码。我怎样才能使它成为可以在不同属性上执行的通用函数?
我尝试包含“prop”参数,但没有成功:
$scope.topScorerSearch = function(prop) {
var topScorers = [];
$scope.teamDetails.squad.forEach(function(o) {
if (o.prop > 0) {
topScorers.push(o)
}
});
return topScorers;
}
...并像这样调用函数:
{{topScorerSearch(goals)}}
为什么这不起作用?我哪里错了?
【问题讨论】:
-
您应该接受解决问题的答案,以便其他人可以一眼看到它已解决(@Sidriel 也得到了他们的观点)。
-
我正要... 就在 3 分钟前,请稍等 :)
-
耐心不是我的菜;)
标签: arrays angularjs foreach properties push