js簡易計算器底層運算邏輯
阿新 • • 發佈:2017-08-29
rip != ring 等於 get flag show war false
var Calc={ getData:function(arr){ var tempStr = ""; var data = []; //格式化數據 for(var i = 0; i < arr.length; i++){ if(Number(arr[i])|| Number(arr[i]) == 0){ tempStr += arr[i] }else{ if(tempStr != ‘‘){ data.push(tempStr); } data.push(arr[i]); tempStr = ‘‘; } } if(tempStr != ‘‘){ data.push(tempStr); tempStr = ‘‘; } //去掉0開頭 for(var i = 0; i < data.length; i++){ if(Number(data[i])|| Number(data[i]) == 0){ data[i] = Number(data[i]) } } if(data[data.length-1] == "="){ var result = Calc.calute(data); data.push(result); } Calc.show(data); }, show:function(arr){ console.log(arr.join("")); }, calute:function(arr){ var newArr = JSON.parse(JSON.stringify(arr)); //根號 while(newArr.indexOf(‘sqrt‘) != -1){ var index = newArr.indexOf(‘sqrt‘); var num1 = newArr[index+1]; var result = Math.sqrt(num1); newArr.splice(index,2,result); } //計算除法 while(newArr.indexOf(‘/‘) != -1){ var index = newArr.indexOf(‘/‘); var num1 = newArr[index-1]; var num2 = newArr[index+1]; var result = num1/num2; newArr.splice(index-1,3,result); } //乘法 while(newArr.indexOf(‘*‘) != -1){ var index = newArr.indexOf(‘*‘); var num1 = newArr[index-1]; var num2 = newArr[index+1]; var result = num1*num2; newArr.splice(index-1,3,result); } //減法 while(newArr.indexOf(‘-‘) != -1){ var index = newArr.indexOf(‘-‘); var num1 = newArr[index-1]; var num2 = newArr[index+1]; var result = num1-num2; newArr.splice(index-1,3,result); } //加法 while(newArr.indexOf(‘+‘) != -1){ var index = newArr.indexOf(‘+‘); var num1 = newArr[index-1]; var num2 = newArr[index+1]; var result = num1+num2; newArr.splice(index-1,3,result); } try{ if(newArr.length > 2){ throw new Error("計算錯誤"); } }catch(e){ console.log(e); console.log(newArr); return "表達式錯誤"; } return newArr[0]; } } var arr = ["0","2","0","+","3","+", "sqrt","4","-","8","="]; Calc.getData(arr); //type: 1:空, 2:數字, 3:運算符, 4:等於 function vaild(oldType,type){ var flag = false; //type == 2時 if((oldType == 1 && type == 2)||(oldType == 2 && type == 2) || (oldType == 3 && type == 2)){ return true; } //type == 3 if(oldType == 2 && type == 3){ flag = true; } //type == 4 if(oldType == 2 && type == 4){ flag = true; } return flag; }
js簡易計算器底層運算邏輯