js简易计算器底层运算逻辑

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js简易计算器底层运算逻辑相关的知识,希望对你有一定的参考价值。

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简易计算器底层运算逻辑的主要内容,如果未能解决你的问题,请参考以下文章

实践js实现简易的四则运算计算器

JS实现简易的计算器

简易前端模板引擎

Java 简易计算器代码(只能整数的简易运算)

揭秘你处理数据的“底层逻辑”,详解公式引擎计算

揭秘你处理数据的“底层逻辑”,详解公式引擎计算