如何解析和评估字符串中的数学表达式(例如'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
更多推荐
发布评论