在JavaScript中将字符串评估为数学表达式 [英] Evaluating a string as a mathematical expression in JavaScript

查看:110
本文介绍了在JavaScript中将字符串评估为数学表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于在JavaScript中将字符串评估为数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆