在JavaScript中将字符串作为数学表达式进行评估(Evaluating a string as a mathematical expression in JavaScript)

系统教程 行业动态 更新时间:2024-06-14 16:59:17
在JavaScript中将字符串作为数学表达式进行评估(Evaluating a string as a mathematical expression in JavaScript)

如何解析和评估字符串中的数学表达式(例如'1+1' ),而不调用eval(string)以产生其数值?

有了这个例子,我希望函数接受'1+1'并返回2 。

How do I parse and evaluate a mathematical expression in a string (e.g. '1+1') without invoking eval(string) to yield its numerical value?

With that example, I want the function to accept '1+1' and return 2.

最满意答案

您可以使用JavaScript Expression Evaluator库 ,它可以让您执行以下操作:

Parser.evaluate("2 ^ x", { x: 3 });

或者mathjs ,它允许的东西像:

math.eval('sin(45 deg) ^ 2');

我最终选择了我的一个项目的mathjs。

I've eventually gone for this solution, which works for summing positive and negative integers (and with a little modification to the regex will work for decimals too):

function sum(string) { return (string.match(/^(-?\d+)(\+-?\d+)*$/)) ? string.split('+').stringSum() : NaN; } Array.prototype.stringSum = function() { var sum = 0; for(var k=0, kl=this.length;k<kl;k++) { sum += +this[k]; } return sum; }

I'm not sure if it's faster than eval(), but as I have to carry out the operation lots of times I'm far more comfortable runing this script than creating loads of instances of the javascript compiler

更多推荐

本文发布于:2023-04-16 14:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/1710f17e1aa9021b73a5917ca7b263a0.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   字符串   中将   数学   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!