问题
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:
As user Pointy noticed, I was calling
compute()
without its required parameters.I should add
console.log()
in myelse
statement before thereturn
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