Javascript 中算术表达式的安全评估 [英] Safe evaluation of arithmetic expressions in Javascript

查看:24
本文介绍了Javascript 中算术表达式的安全评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Javascript 中评估用户输入的算术表达式,例如2 * (3 + 4)",但出于安全原因我不想使用 eval.

I need to evaluate user-entered arithmetic expressions like "2 * (3 + 4)" in Javascript but I don't want to use eval for security reasons.

我可以去掉所有不是数字或运算符的字符,但我不确定这是否是安全的,如果用户可以使用像 cossqrt 等...

I could strip out all the characters that are not numbers or operators but I'm not sure this would be safe anyway and it would be nice if the user could use functions like cos, sqrt, etc...

是否有进行算术表达式求值的 Javascript 库?

Are there any Javascript libraries that do arithmetic expression evaluation?

推荐答案

你可以试试JavaScript Expression Evaluator:

这个库是一个修改过的版本Raphael Graf 的 ActionScript 表达式解析器.当我写 JavaScript 的时候函数绘图仪,我想要一个更好的使用 JavaScript 的 eval 的替代方法功能.没有安全风险目前,因为你只能运行在你自己的浏览器中编写代码,但它不是为数学方便 (Math.pow(2^x)而不是 2^x 等).

This library is a modified version of Raphael Graf’s ActionScript Expression Parser. When I wrote the JavaScript Function Plotter, I wanted a better alternative to using JavaScript’s eval function. There’s no security risk currently, because you can only run code in your own browser, but it’s not as convenient for math (Math.pow(2^x) instead of 2^x, etc.).

那么你的代码将是这样的:

then your code will be like that:

console.info ( Parser.evaluate( "2 * (3 + 4)" ) ); //prints 14

这篇关于Javascript 中算术表达式的安全评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆