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

时间:2019-04-28 13:48:08

标签: javascript function object

我在一个小型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'

我真的只想将“ challenge2()”函数的返回值保存在一个简单的变量中。我究竟做错了什么? 调试显示其未定义。

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

ParentNode.append不会返回任何内容,也就是undefined。当您从appendStringBuilder返回该调用的结果,然后再次返回并最终将其分配给变量时,变量的末尾为undefined也就不足为奇了。

答案 1 :(得分:1)

append返回undefined。您可能打算这样做

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

答案 2 :(得分: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);