我正在尝试实现forEach javascript函数来迭代players
数组并总计一些值。当我调用该函数时,我收到错误
players.forEach(function(players){
^
TypeError: undefined is not a function
代码在这里:
/*calculate the total number of points per player, use to calculate total score*/
function playerTotal(playerObj){
var pacersTotal = 0;
var hawksTotal = 0;
var total = 0;
total += 3*(playerObj.three_pointers_made);
total += 2*(playerObj.field_goals_made - playerObj.three_pointers_made);
total += playerObj.free_throws_made;
if (playerObj.team_name == "Pacers"){
pacersTotal += total;
}
else {
hawksTotal += total;
}
console.log("Pacers " + pacersTotal + "\nHawks" + hawksTotal);
}
players.forEach(playerTotal(players));
换句话说,我尝试使用forEach在playerTotal
数组中的每个值(对象)上调用players
函数,但无效!有什么提示吗?
答案 0 :(得分:7)
假设您在调用players
方法之前定义了forEach
,问题就是这一行
players.forEach(playerTotal(players));
应该传递功能参考而不是功能响应。
制作
players.forEach(function(playerObj){
playerTotal(playerObj);
});