如何将字符串公式转换为使用JavaScript数值 [英] How to convert a string equation to a numeric value with Javascript

查看:130
本文介绍了如何将字符串公式转换为使用JavaScript数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个用户输入字段用户可以在其中输入一个数字。 他们希望也能够在输入字段中输入公式为好。

Basically, I have a user input field where a user can enter a number. They would like to also be able to enter equations in the input field as well.

类似于874.45 * 0.825 + 4000并有转化为它的实际数值。

Something like "874.45 * 0.825 + 4000" and have that converted to its real numeric value.

所有的解决方案,我发现点到可怕的的eval()方式。特别是随着这是一个用户输入的字段,我关心的只是运行的的eval(874.45 * 0.825 + 4000),并希望能得到一些从后端。

All the solutions I found point to the dreaded eval() method. Especially with this being a user entered field, I'm concerned about just running eval("874.45 * 0.825 + 4000") and hoping to get a number out the back end.

我想我可以做一个Web服务调用回服务器(ASP.NET),但恐怕有轻微的延迟会造成一些来自用户的无奈。

I suppose I could do a web service call back to the server (ASP.NET), but I'm afraid a slight delay will create some frustration from the user.

有谁知道任一个很好的技术或者现有的库,可以为我做的?

Does anyone know of either a good technique or existing libraries that could do this for me?

推荐答案

你真正需要的是这里的前pression分析器,因为你想用户EX preSS它们的值用允许一个小的领域特定语言。

What you really need here is an "expression parser", because you're trying to allow users to express their values using a small domain-specific language.

的基本机制的工作是这样的:

The basic mechanics work like this:

  1. 标记化的​​EX pression为运营商和操作数。

  1. Tokenize their expression into operators and operands.

根据操作(例如,其中乘法的求优先级高于加成)的量级上,按下操作符和操作数入栈

Based on the order of operations (e.g, where multiplication is evaluated with higher priority than addition), push the operators and operands onto a stack.

从弹出堆栈操作数和中间结果回推入堆栈。重复,直到堆栈为空。

Pop the operands from the stack and push intermediate results back onto the stack. Repeat until the stack is empty.

我已经在我的项目做过一个极大次不同的小语言。但从来没有在JavaScript中。所以,我不能直接推荐合适的解析库。

I've done this a gazillion times for different "little languages" throughout my projects. But never in javascript. So I can't directly recommend a suitable parsing library.

但快速谷歌搜索发现PEG.js。看看这里:

But a quick googling reveals "PEG.js". Check it out here:

http://pegjs.majda.cz/

所有其文档的例子是正是那种你想打造EX pression分析器的。

All of the examples in their documentation are for exactly the kind of "expression parser" you're trying to build.

这篇关于如何将字符串公式转换为使用JavaScript数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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