Uncaught SyntaxError: Unexpected identifier at compute

瘦欲@ 提交于 2021-01-01 06:44:23

问题


I have some code that returns an Uncaught SyntaxError when I run it but I don't understand why.

I tried putting it through JSHint but to no avail.

Here is the code that is apparently wrong:

function compute(expr, x, string) {
  var whatisx = "x=" + toString(x) + ",";
  var tempAns = parseFloat(eval(whatisx + expr));
  var roundedAnswer = roundNumber(tempAns, 3);
  if (isNaN(tempAns) === true) {
    alert("error");
  }
  if (string) {
    return toString(roundedAnswer);
  } else if (!string) {
    return roundedAnswer;
  } else {
    return null;
    console.log("Error trying to compute value. The string value must be boolean.");
  }
}

When I run it, I don't get any console logs and it says there is an error at the plus sign in:

var tempAns = parseFloat(eval(whatisx + expr));

Another problem in the same program that is also a SyntaxError is in my HTML.

Here is my html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Grapher</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js" charset="utf-8"></script>
    <script type="text/javascript" src="functions.js" charset="utf-8"></script>
    <script type="text/javascript" src="sketch.js" charset="utf-8"></script>
  </head>
  <body>
    <form>
      <label>Graph y=</label>
      <input id="mathExpr" type="text" name="mathExpr" value="">
      <label> from x=</label>
      <input id="x_min" type="text" name="x_min" value="">
      <label> to </label>
      <input id="x_max" type="text" name="x_max" value="">
      <input type="button" name="result" value="Result" onclick="compute(); runp5();">
    </form>
    <h2>Answer: <span id="output"></span></h2>
  </body>
</html>

For this one, it says there is an error at

<input type="button" name="result" value="Result" onclick="compute(); runp5();">

What can I do to fix both of those? Thanks in advance.

Edit: Question resolved. I was calling compute without any parameters. (thanks @Pointy)


回答1:


I came back to this question just now, and I realized I was making another mistake. Here is my fix:

  1. As user Pointy noticed, I was calling compute() without its required parameters.

  2. I should add console.log() in my else statement before the return otherwise it won't get called at all:

// ...

else {
  console.log('message'); // this should come before return
  return null;
} 

This doesn't actually fix the problem I detailed, but I wanted to point it out for any future readers.



来源:https://stackoverflow.com/questions/56654859/uncaught-syntaxerror-unexpected-identifier-at-compute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!