Evaluating strings containing formulas is a common task in programming. While JavaScript offers the eval() function for such purposes, it presents security risks and is generally discouraged. Here's an alternative approach to calculate string values without using eval().
The Function() constructor can create anonymous functions from strings. This can be utilized to evaluate string expressions. For example, consider the following code:
function evil(fn) { return new Function('return ' + fn)(); } console.log(evil('12/5*9+9.4*2')); // => 40.4
By returning a new function evaluated by the Function() constructor, we can execute mathematical operations stored in strings. In this example, the string "12/5*9+9.4*2" is evaluated to 40.4.
Compared to eval(), the Function() constructor allows for:
While the Function() constructor offers a more secure and reliable alternative to eval(), it's important to note that it still evaluates code dynamically, so precautions should be taken to avoid malicious inputs.
Das obige ist der detaillierte Inhalt vonWie werte ich String-Formeln in JavaScript aus, ohne eval() zu verwenden?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!