javascript 将等式字符串转换为等式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14263024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:10:05  来源:igfitidea点击:

Convert equation string to equation

javascript

提问by maxhud

Possible Duplicate:
Running an equation with Javascript from a text field

可能的重复:
从文本字段中使用 Javascript 运行方程式

How can I convert the following:

我如何转换以下内容:

var n = "2x^3+3x+6";

To

var x = a number
var n = 2x^3+3x+6;

In JavaScript?

在 JavaScript 中?

回答by tjdecke

Quite hard to guess what the exact requirements and the context are, but if you want to roughly stick to the grammar demonstrated by your variable I'd suggest using a math expression parser.

很难猜测确切的要求和上下文是什么,但是如果您想粗略地坚持您的变量所展示的语法,我建议您使用数学表达式解析器。

Using js-Expression-eval, it could look like this:

使用js-Expression-eval,它可能如下所示:

var formula = "2*x^3+3*x+6";
var expression = Parser.parse(formula);
var result = expression.evaluate({ x: 3 });

Run the Fiddle

运行小提琴

Should you want to have your own grammar - to leave out the * symbols for multiplication with variables, for example - you'll have to roll your own parser, for example using something like jison.

如果您想拥有自己的语法 - 例如,省略用于与变量相乘的 * 符号 - 您必须推出自己的解析器,例如使用jison 之类的东西

回答by Micha?l Benjamin Saerens

var x = a number;
var n = eval("2*Math.pow(x,3)+3*x+6")