Evaluating a string as a mathematical expression in JavaScript

前端 未结 16 2016
我在风中等你
我在风中等你 2020-11-22 03:34

How do I parse and evaluate a mathematical expression in a string (e.g. \'1+1\') without invoking eval(string) to yield its numerical value?

<
16条回答
  •  粉色の甜心
    2020-11-22 04:17

    I went looking for JavaScript libraries for evaluating mathematical expressions, and found these two promising candidates:

    • JavaScript Expression Evaluator: Smaller and hopefully more light-weight. Allows algebraic expressions, substitutions and a number of functions.

    • mathjs: Allows complex numbers, matrices and units as well. Built to be used by both in-browser JavaScript and Node.js.

提交回复
热议问题