我有一系列玩家,每个玩家都是一个具有多个属性的对象,一个是“目标”。
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)}}
为什么这不起作用?我哪里错了?
答案 0 :(得分:2)
我认为问题是prop
无法解析为goals
因为goals
被视为具有null或undefined值的变量,因此prop prop为null或undefined。
如果您使用替代方法访问对象属性object["property"]
并使用函数{{topScorers("goals")}}
,它应该可以解决。