isNan函数使下一行代码不起作用

时间:2018-04-11 18:27:25

标签: javascript html

所以,这是我的jsfiddle:

https://jsfiddle.net/therealnemis/dxrdo9km/87/

正如你在heron()中看到的,我有三行代码,第三行是用“answer”改变标签,在我的HTML中用h3标签。如果我将标签放在第二行,那么当我按下标有“Something”的按钮时,代码将会执行:

    var answer = squareRoot(15);

  //If the answer is NaN, this is due to the fact that the triangle is not possible.
 document.getElementById("answer").innerHTML = squareRoot(15);
 result = checkIfRealTriangle(answer);

当我按下标记为Something的按钮时,这是有效的,因为document.GetElementById位于checkIfRealTriangle之前,后者包含isNaN函数。如果我将getelementbyID移动到isNaN函数下面,那么当我按下标记为Something的按钮时,什么都不会发生。如果我摆脱isNaN,一切正常。

2 个答案:

答案 0 :(得分:2)

您需要定义checkIfRealTriangle(answer)函数中的“area”变量。如果你在控制台中查看,你会看到错误。

答案 1 :(得分:1)

这是您的问题功能:

function checkIfRealTriangle(answer) {
  var output;
  if (isNaN(answer)) {
    output = "Your sides do not make a real triangle. Check your numbers and try again";
  } else {
    output = "The Area of your triangle is " + area;
  }
  return output;
}

当传递一个为isNaN(即15)返回false的数字时,此函数返回以下错误:

  

未捕获的ReferenceError:未定义区域       at checkIfRealTriangle(:8:48)       at:1:1

您需要更换" area"用"回答"像这样:

function checkIfRealTriangle(answer) {
  var output;
  if (isNaN(answer)) {
    output = "Your sides do not make a real triangle. Check your numbers and try again";
  } else {
    output = "The Area of your triangle is " + answer;
  }
  return output;
}