我需要一个计算器应用程序的评估替代方案



我在计算函数中使用eval。我想使用一种替代方案,但在线搜索会导致我找到非常复杂的解决方案,或者需要我完全重写代码。有没有什么方法可以在计算函数中使用其他东西,而不必大幅更改我的代码的其余部分?

这是我的App.js代码

import Buttons from "./components/Buttons";
import Display from "./components/Display";
import {useState} from "react";
import Screen from "./components/Screen";

function App() {
const [disp, setDisp] = useState("")
const [value, setValue] = useState("")
function handleChange(event) {
const input = event.target.value
setValue(prevState => prevState + input)
setDisp(input)
}
function errorCatch() {
setValue(prevState => 
prevState === "+" ||
prevState === "*" ||
prevState === "/" ||
prevState === "-+" ||
prevState === "-*" ||
prevState === "-/" ||
prevState === "--"
? setDisp("ERROR")
: prevState.length > 20
? setDisp("MAX LIMIT REACHED")
: prevState)
}
function calculate() {
setDisp(eval(value))
setValue(value)

}
function backspace() {
setValue(value.slice(0, -1))
setDisp(disp.slice(0, -1))
}
function clear() {
setValue("")
setDisp("")
}
return (
<div className="App">
<div className="calculator">
<Screen value={value}/>
<Display disp={disp}/>
<Buttons handleChange={handleChange} calculate={calculate} backspace={backspace} clear={clear} errorCatch={errorCatch}/>
</div>
</div>
);
}
export default App;

这是我的Buttons.js代码


const btnValues = [
["AC", "DEL", "/"],
[7, 8, 9,"*"],
[4, 5, 6, "-"],
[1, 2, 3, "+"],
[0, ".", "="]
]

export default function Buttons(props) {  
return (
<div className="buttons">
{
btnValues.flat().map((i) => {
return (
<button 
key={i}
value={i}
onClick={(e) =>
i === "AC"
? props.clear(e)
: i === "="
? props.calculate(e)
: i === "DEL"
? props.backspace(e)
: props.handleChange(e) || props.errorCatch(e)
}
className={
i === "AC" ? "AC" :
i === "=" ? "equal" :
i === "/" || i === "*" || i === "+" || i === "-" ? "light" :
""
}
>{i}</button>
)
})
}
</div>
)
}

您似乎正在尝试构建与本文非常相似的东西。

在本文中搜索关于compute函数的部分,您会发现有一个简单的解析器,它可以在不使用eval的情况下解析输入并计算输出。

为了方便您,我在这里处理相关功能:

compute() {
let computation
const prev = parseFloat(this.previousOperand)
const current = parseFloat(this.currentOperand)
if (isNaN(prev) || isNaN(current)) return
switch (this.operation) {
case '+':
computation = prev + current
break
case '-':
computation = prev - current
break
case '*':
computation = prev * current
break
case '÷':
computation = prev / current
break
default:
return
}
this.currentOperand = computation
this.operation = undefined
this.previousOperand = ''
}

最新更新