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

查看:34
本文介绍了在 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

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

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