在const中保存函数返回是未定义的

问题描述 投票:0回答:3

我在一个小型的JS应用程序上挑战自己,它关于一些篮球队,我正在计算三场比赛的平均得分。我被困在一个基本的东西,我不明白。

首先是代码:

// simple stringbuilder function
function appendStringBuilder(string, tag) {
  return document.querySelector(tag).append(string);
}

// function calculates average score of team
function avgScoreCalc(obj) {
  const values = Object.values(obj);
  let avgSum = 0;
  for (var i = 0; i < values.length; i++) {
    if (Number.isInteger(values[i])) {
      avgSum += values[i];
    }
  }
  avgSum = avgSum / 3;
  return Math.round(avgSum);
}

function challenge2(ObjName, teamName, firstGame, secondGame, thirdGame) {
  var ObjName = {
    teamName: teamName,
    firstGame: firstGame,
    secondGame: secondGame,
    thirdGame: thirdGame,
  };
  avgScoreCalc(ObjName);
  return appendStringBuilder(`${ObjName.teamName}: ${avgScoreCalc(ObjName)} | `, '.code-output-2');
  }

// IS UNDEFINED, WHY? <<<<
const TJohn = challenge2('TJohn', 'Team John', 89, 120, 103);
//----------------------------------------------------------

console.log(TJohn); //<<<< 'undefined'

我真的只想在一个简单的var中保存“challenge2()”函数的返回。我究竟做错了什么?调试说它未定义。

谢谢你的帮助。

javascript function object
3个回答
1
投票

append返回undefined。你可能想做

function appendStringBuilder(string, tag) {
  document.querySelector(tag).append(string);
  return string;
}

1
投票

ParentNode.append确实没有返回,也就是undefined。当你从appendStringBuilder返回该调用的结果,并再次返回到最后将它分配给变量时,变量最后是undefined就不足为奇了。


0
投票
It looks like the signature of challenge2 function having ObjName is not of any use as again you are creating a variable inside with same name. Also other functions you are using inside not having any definition.

Find the updated 'challenge2' function which will work for same. (still can be optimized)

// function calculates average score of team

    function avgScoreCalc(obj) {
      const values = Object.values(obj);
      let avgSum = 0;
      for (var i = 0; i < values.length; i++) {
        if (Number.isInteger(values[i])) {
          avgSum += values[i];
        }
      }
      avgSum = avgSum / 3;
      return Math.round(avgSum);
    }

    function challenge2( teamName, firstGame, secondGame, thirdGame) {

      var ObjName = {
        teamName: teamName,
        firstGame: firstGame,
        secondGame: secondGame,
        thirdGame: thirdGame,
      };

      return `${ObjName.teamName}  :  ${avgScoreCalc(ObjName)}`;

    }

    const TJohn = challenge2( 'Team John', 89, 120, 103);
    //----------------------------------------------------------

    console.log(TJohn);
© www.soinside.com 2019 - 2024. All rights reserved.