且构网

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

在JavaScript中将字符串评估为数学表达式

更新时间:2021-12-14 03:29:30

我最终为这个解决方案而去,它可用于求和正整数和负整数(并且对正则表达式进行一些修改也适用于小数):

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