Function evaluate #

计算表达式。

表达式解析器不使用 JavaScript。其语法接近 JavaScript,但更适合数学表达式。请参阅 https://mathjs.cn/docs/expressions/syntax.html 了解语法并概览与 JavaScript 的确切区别。

请注意,评估任意表达式可能存在安全风险,请参阅 https://mathjs.cn/docs/expressions/security.html 获取更多信息。

Syntax #

math.evaluate(expr)
math.evaluate(expr, scope)
math.evaluate([expr1, expr2, expr3, ...])
math.evaluate([expr1, expr2, expr3, ...], scope)

Parameters #

Parameter Type Description
expr string | string[] | Matrix 要计算的表达式
scope Object 用于读/写变量的范围

Returns #

Type Description
* 表达式的结果

Throws #

Type Description
Error  

Examples #

math.evaluate('(2+3)/4')                // 1.25
math.evaluate('sqrt(3^2 + 4^2)')        // 5
math.evaluate('sqrt(-4)')               // 2i
math.evaluate(['a=3', 'b=4', 'a*b'])    // [3, 4, 12]

let scope = {a:3, b:4}
math.evaluate('a * b', scope)           // 12

另请参阅 #

parse, compile

Fork me on GitHub