[英]Reactjs - SyntaxError: Octal literals are not allowed in strict mode
I have the following code for my app component in reactjs:我的应用程序组件在 reactjs 中有以下代码:
function App() {
var [expression, setExpression] = useState("");
var [result, setResult] = useState("");
return (
<div className="App">
<div id="equals">
{result}
</div>
<div id="display">
{expression}
</div>
<button id='zero' onClick={() => setExpression(expression + "0")}>0 </button>
<button id='one' onClick={() => setExpression(expression + "1")}>1 </button>
<button id='two' onClick={() => setExpression(expression + "2")}>2 </button>
<button id='three' onClick={() => setExpression(expression + "3")}>3 </button>
<button id='four' onClick={() => setExpression(expression + "4")}>4 </button>
<button id='five' onClick={() => setExpression(expression + "5")}>5 </button>
<button id='six' onClick={() => setExpression(expression + "6")}>6 </button>
<button id='seven' onClick={() => setExpression(expression + "7")}>7 </button>
<button id='eight' onClick={() => setExpression(expression + "8")}>8 </button>
<button id='nine' onClick={() => setExpression(expression + "9")}>9 </button>
<button id="add" onClick={() => setExpression(expression + "+")}>+</button>
<button id="subtract" onClick={() => setExpression(expression + "-")}>-</button>
<button id="multiply" onClick={() => setExpression(expression + "*")}>*</button>
<button id="divide" onClick={() => setExpression(expression + "/")}>/</button>
<button id="equals" onClick={() => setResult(eval(expression))}>=</button>
</div>
);
}
But when I open the browser I get the error:但是当我打开浏览器时,我得到了错误:
SyntaxError: Octal literals are not allowed in strict mode.
I don't know how to fix it though.我不知道如何解决它。 Thanks in advance.提前致谢。
This is a bit subtle.这有点微妙。 The issue is that you're concatenating strings.问题是您正在连接字符串。 At some point, it would appear you've clicked the 0
button followed by any of the other digit buttons.在某些时候,您似乎单击了0
按钮,然后单击了任何其他数字按钮。 That means you end up with expression
being "01"
or similar.这意味着你最终的expression
是"01"
或类似的。 That's a legacy octal literal, which (as you've discovered) are disallowed in strict mode.这是一个遗留的八进制文字,(正如您所发现的)在严格模式下是不允许的。
You'll need to update your code that adds to the expression so that when it's about to add the digit 1 through 9, it looks to see if there's a 0
(and only a 0
) after the last operator and, if so, removes that 0
before adding the digit.您需要更新添加到表达式中的代码,以便在即将添加数字 1 到 9 时,它会查看最后一个运算符之后是否有0
(并且只有0
),如果有,则删除添加数字之前的那个0
。
For instance, if expression
is "1+0"
, clicking 2
should remove that "0"
before adding the "2"
so that it ends up being "1+2"
, not "1+02"
.例如,如果expression
是"1+0"
,单击2
应该在添加"2"
" 之前删除那个"0"
,这样它最终是"1+2"
,而不是"1+02"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.