如何在不调用 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 中的数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
即使在调用 abort (jQuery) 之后,浏览器也会等待Browser waits for ajax call to complete even after abort has been called (jQuery)(即使在调用 abort (jQuery) 之后,浏览器也会等待 ajax 调用
JavaScript innerHTML 不适用于 IE?JavaScript innerHTML is not working for IE?(JavaScript innerHTML 不适用于 IE?)
XMLHttpRequest 无法加载,请求的资源上不存在“AXMLHttpRequest cannot load, No #39;Access-Control-Allow-Origin#39; header is present on the requested resource(XMLHttpRequest 无法加载,请求的资
XHR HEAD 请求是否有可能不遵循重定向 (301 302)Is it possible for XHR HEAD requests to not follow redirects (301 302)(XHR HEAD 请求是否有可能不遵循重定向 (301 302))
XMLHttpRequest 206 部分内容XMLHttpRequest 206 Partial Content(XMLHttpRequest 206 部分内容)
XMLHttpRequest 的 getResponseHeader() 的限制?Restrictions of XMLHttpRequest#39;s getResponseHeader()?(XMLHttpRequest 的 getResponseHeader() 的限制?)