forEach javascript函数未定义

时间:2016-02-16 08:06:24

标签: javascript foreach

我正在尝试实现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函数,但无效!有什么提示吗?

1 个答案:

答案 0 :(得分:7)

假设您在调用players方法之前定义了forEach问题就是这一行

players.forEach(playerTotal(players));

应该传递功能参考而不是功能响应

制作

players.forEach(function(playerObj){

   playerTotal(playerObj);

});