原文:
怎樣 計算檔案中運算式的值,並輸出到運算式後面,有多個運算式,但每行有一個運算式檔案中內容 23+4*35-9*4= 4*(3+7-9/3)-45/5= 3+4*32/(8*2)= 24-((9+45)/3)= 將結果輸出到等號後面
沒仔細研究JavaScript引擎實現的eval的C源碼;暫用JavaScript實現,線上測試http://jsfiddle.net/fuweichin/AL5Zf/
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8" /><title> New Document </title><style type="text/css">label{display:block;margin-bottom:5px;}</style></head><body><form action=""><label for="file"><textarea id="file" style="width:320px;height:240px;overflow:auto;">23+4*35-9*4=4*(3+7-9/3)-45/5=3+4*32/(8*2)=24-((9+45)/3)=</textarea></label><label for="calc"><button type="button" id="calc">Eval</button></label></form><script type="text/javascript">/*require*/if(!String.prototype.trim)String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"");};if(!Array.prototype.forEach)Array.prototype.forEach=function(fn, s) {var t=this,l=t.length;for (var i=0; i<l; i++)fn.call(Object(s), t[i], i, t);};/*main*/(function(window){var get=function(id){return window.document.getElementById(id);};var getLines=function(){var text=get("file").value.trim();if(text){return text.split(/\n+/);}else{return [];}};var evalLines=function(event){var lines=getLines();//console.log(lines.join(","));var newlines=new Array();lines.forEach(function(line,index){line=line.trim();var expr=line.split("=")[0];var value="";try{value=eval("("+expr+")");if(typeof value!="number"||!isFinite(value)){value="";}}catch(_){}finally{newlines[index]=expr+"="+value;}});get("file").value=newlines.join("\n");};get("calc").onclick=evalLines;})(window);</script></body></html>