将字符串计算为 JavaScript 中的数学表达式
如何在不调用 eval(string)
的情况下解析和评估字符串中的数学表达式(例如 '1+1'
)以产生其数值?
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?
在这个例子中,我希望函数接受 '1+1'
并返回 2
.
With that example, I want the function to accept '1+1'
and return 2
.
推荐答案
我最终选择了这个解决方案,它适用于对正整数和负整数求和(对正则表达式稍作修改也适用于小数):
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;
}
我不确定它是否比 eval() 快,但由于我必须多次执行该操作,因此运行此脚本比创建大量 javascript 编译器实例更舒服
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
相关文章