問題描述
如何在不調(diào)用 eval(string)
的情況下解析和評估字符串中的數(shù)學(xué)表達(dá)式(例如 '1+1'
)以產(chǎn)生其數(shù)值?
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?
在這個(gè)例子中,我希望函數(shù)接受 '1+1'
并返回 2
.
With that example, I want the function to accept '1+1'
and return 2
.
推薦答案
我最終選擇了這個(gè)解決方案,它適用于對正整數(shù)和負(fù)整數(shù)求和(對正則表達(dá)式稍作修改也適用于小數(shù)):
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() 快,但由于我必須多次執(zhí)行該操作,因此運(yùn)行此腳本比創(chuàng)建大量 javascript 編譯器實(shí)例更舒服
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
這篇關(guān)于將字符串計(jì)算為 JavaScript 中的數(shù)學(xué)表達(dá)式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!