对于未定义每个 JavaScript 函数

forEach javascript function not defined

本文关键字:JavaScript 函数 未定义      更新时间:2023-09-26

我正在尝试实现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 对players数组中的每个值(对象(调用 playerTotal 函数,但无济于事!有什么提示吗?

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

players.forEach(playerTotal(players));

它应该传递函数引用而不是函数响应

来得及

players.forEach(function(playerObj){
   playerTotal(playerObj);
});