且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串公式转换为使用JavaScript数值

更新时间:2023-11-08 17:31:04

你真正需要的是这里的前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.