function CalcVar(str,isConst){ this.str=str; this.isConst=isConst; this.type=1; } CalcVar.prototype.getVal=function(varobj){ if(this.isConst) return parseFloat(this.str)||0; return parseFloat(varobj[this.str]); }; CalcVar.prototype.nextTypes=function(){ return [2,4]; }; CalcVar.prototype.toString=function(){ var prefix=''; if(!this.isConst){ prefix='['; return prefix+this.str+']'; } return prefix+this.str; }; function CalcOp(str){ this.str=str; this.type=2; } CalcOp.prototype.nextTypes=function(){ return [1,3]; }; CalcOp.prototype.getLevel=function(){ if(this.str=='*' || this.str=="/"){ return 2; } return 1; }; CalcOp.prototype.calc=function(num1,num2){ var str=this.str; if(str=='+'){ return num1+num2; }else if(str=='-'){ return num1-num2; }else if(str=='*'){ return num1*num2; }else if(str=='/'){ if(num2==0) throw new Error("被除数不能为0"); return num1/num2; } }; CalcOp.prototype.toString=function(){ return this.str; }; function CalcLBrace(){ this.type=3; } CalcLBrace.prototype.nextTypes=function(){ return [1,3]; }; CalcLBrace.prototype.toString=function(){ return "("; }; function CalcRBrace(){ this.type=4; } CalcRBrace.prototype.nextTypes=function(){ return [2,4]; }; CalcRBrace.prototype.toString=function(){ return ")"; }; function ParseFormula(calcStr){ var calcarr=[]; for(var i=0;i=0){ var calcobj=new CalcOp(val); calcarr.push(calcobj); }else if(val=='['){ var vname='['; while(i0 && opStack[opStack.length-1].getLevel()>=calcobj.getLevel()){ var op=opStack.pop(); var num2=numStack.pop(); var num1=numStack.pop(); numStack.push(op.calc(num1,num2)); } opStack.push(calcobj); }else if(calcobj.type==4){ while(opStack.length>0){ var op=opStack.pop(); var num2=numStack.pop(); var num1=numStack.pop(); numStack.push(op.calc(num1,num2)); } return [numStack[0],i]; }else if(calcobj.type==3){ var arr=helperFormula(calcarr,i+1,vars); numStack.push(arr[0]); i=arr[1]; } } while(opStack.length>0){ var op=opStack.pop(); var num2=numStack.pop(); var num1=numStack.pop(); numStack.push(op.calc(num1,num2)); } return [parseFloat((numStack[0]).toFixed(6)+0.000001), -1]; }