javascript - 如何在 javascript 计算器中检测和存储操作符前后的数字?

标签 javascript html css

这个元素一定是大家尝试做的最普遍的元素了。我已经按照 Udemy 上的教程完成了它。但现在我想用我自己的逻辑和自己的解决问题策略来制作一个计算器。

问题-:我的计算器应用程序目前有 2 个问题。 1) 用户只能输入一位数字进行计算。我希望它适用于 10 位数字。 2)使按钮工作。 我会尽力让您理解这个问题,因为它有点不同。 例如-: 用户输入数字 12 然后他按下 + 然后他按下 16

预期输出-:

发生 12+16 加法,输出为 28。

目前的问题-: 首先,用户甚至不能输入 12。他一次只能输入 1 个数字。 此外,当他按下加法时,没有执行计算的函数因为我在考虑如何在他按下任何运算符之前和之后检测用户输入,然后将其保存到一些变量并按照运营商。

我现在的代码-:

 <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>Calculator</title>
    	<style>
    		
    	input
    {
    	height:100px;
    	width:150px;
    
    	border-radius:10px;
     	border-style:none;
     	background-color:black;
     	color:white;
    
    }
    .abcde 
    /*for display purposes*/
    {
    	background-color:blue;
    	height:100px;
    	width:608px;
    	border-radius: 10px;
    	color:white;
    	font-size:100px;
    
    
    }
    		
    	</style>
    
    	<h1>Basic calculator</h1>
    </head>
    <body>
    
    	<script>
    		// function clearfunc()
    		// {
    		// 	document.getElementById("abcd").innerHTML="0";
    		// }
    		function show(id)
    		{
    	if(id=="zero")
    	document.getElementById("abcd").innerHTML="0";
    
    	if(id=="one")
    	document.getElementById("abcd").innerHTML="1";
    		
        if(id=="two")
    		document.getElementById("abcd").innerHTML="2";
    	if(id=="plus")
    		document.getElementById("abcd").innerHTML="+";
    	if(id=="three")
    		document.getElementById("abcd").innerHTML="3";
        if(id=="four")
    		document.getElementById("abcd").innerHTML="4";
    	if(id=="five")
    		document.getElementById("abcd").innerHTML="5";
    	if(id=="minus")
    		document.getElementById("abcd").innerHTML="-";
    	if(id=="six")
    		document.getElementById("abcd").innerHTML="6";
    	if(id=="seven")
    		document.getElementById("abcd").innerHTML="7";
    	if(id=="eight")
    		document.getElementById("abcd").innerHTML="8";
    	if(id=="mul")
    		document.getElementById("abcd").innerHTML="*";
    	if(id=="nine")
    		document.getElementById("abcd").innerHTML="9";
    	if(id=="clear")
    		document.getElementById("abcd").innerHTML="";
    
    	if(id=="divide")
    	document.getElementById("abcd").innerHTML="/";
    		
    
    	if(id=="equal")
    		
    document.getElementById("abcd").innerHTML="=";
    	
    
    		}
    
    
    		
    
    		
    		// function show1()
    		// {
    		// 	var a=document.getElementById("zero123").value;
    		// 	document.getElementById("abcd").innerHTML="0";
    		// }
    
    
    
    
    	</script>
    
    <div class="abcde" id="abcd">
    	
    </div>
    
    		<input type="button" value="0" id="zero" onclick="return show(this.id)">
    		<input type="button" value="1" id="one" onclick="return show(this.id)">
    		<input type="button" value="2" id="two" onclick="return show(this.id)">
    		<input type="button" value="+" id="plus" onclick="return show(this.id)"> <br>
    		<input type="button" value="3" id="three" onclick="return show(this.id)">
    		<input type="button" value="4" id="four" onclick="return show(this.id)">
    		<input type="button" value="5" id="five" onclick="return show(this.id)">
    		<input type="button" value="-" id="minus" onclick="return show(this.id)"> <br>
    		<input type="button" value="6" id="six" onclick="return show(this.id)">
    		<input type="button" value="7" id="seven" onclick="return show(this.id)">
    		<input type="button" value="8" id="eight" onclick="return show(this.id)">
    		<input type="button" value="*" id="mul" onclick="return show(this.id)"> <br>
    		<input type="button" value="9" id="nine" onclick="return show(this.id)">
    		<input type="button" value="C" id="clear" onclick="return show(this.id)">
    		<input type="button" value="=" id="equal" onclick="return show(this.id)">
    		
    	
    		<input type="button" value="&#247;" id="divide" onclick="return show(this.id)">
    
    		
    </body>
    </html>

最佳答案

1) Users can enter only 1 digit number for calculation. I want it to work for 10 digit numbers.

您必须编写逻辑来附加您的代码中未完成的现有值,在您的代码中它将始终替换为新值。

2)To make the buttons work. I will try my best to make you understand this problem as it is a bit different. for eg-: user enters digit 12 then he presses + then he presses 16

这不是用户输入的唯一问题 22+22+33+45然后按=进行计算

对于每个值和运算符,你不能有变量所以我在这里使用了 regex 这将防止用户输入无效的表达式,我们只会在用户输入 = 按钮时执行计算

    <html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Calculator</title>
      <style>
         input
         {
         height:100px;
         width:150px;
         border-radius:10px;
         border-style:none;
         background-color:black;
         color:white;
         }
         .abcde 
         /*for display purposes*/
         {
         background-color:blue;
         height:100px;
         width:608px;
         border-radius: 10px;
         color:white;
         font-size:100px;
         }
      </style>
      <h1>Basic calculator</h1>
   </head>
   <body>
      <div class="abcde" id="abcd">
      </div>
      <input type="button" value="0" id="zero" onclick="return show(this.id)">
      <input type="button" value="1" id="one" onclick="return show(this.id)">
      <input type="button" value="2" id="two" onclick="return show(this.id)">
      <input type="button" value="+" id="plus" onclick="return show(this.id)"> <br>
      <input type="button" value="3" id="three" onclick="return show(this.id)">
      <input type="button" value="4" id="four" onclick="return show(this.id)">
      <input type="button" value="5" id="five" onclick="return show(this.id)">
      <input type="button" value="-" id="minus" onclick="return show(this.id)"> <br>
      <input type="button" value="6" id="six" onclick="return show(this.id)">
      <input type="button" value="7" id="seven" onclick="return show(this.id)">
      <input type="button" value="8" id="eight" onclick="return show(this.id)">
      <input type="button" value="*" id="mul" onclick="return show(this.id)"> <br>
      <input type="button" value="9" id="nine" onclick="return show(this.id)">
      <input type="button" value="C" id="clear" onclick="return show(this.id)">
      <input type="button" value="=" id="equal" onclick="return show(this.id)">
      <input type="button" value="&#247;" id="divide" onclick="return show(this.id)">
   </body>
   <script>

      //1. when load add initial "0" in div
      document.getElementById("abcd").innerHTML="0";


      function show(id)
      {

          let existingValue = document.getElementById("abcd").innerHTML

          if(existingValue ==="0") {
            // 2. in case of user enters "0", and "0" already exist then we make div as empty
              existingValue = ""
          }

          /*
            3. instead always setting value using following way, can store it in a variable than store it
            so it would more readable.

            document.getElementById("abcd").innerHTML="2"; // instead we store it like -> nextValue = "2"
            document.getElementById("abcd").innerHTML="+"; // instead we store it like -> nextValue = "+"
          */
          let nextValue = "";


          if(id==="zero")
              nextValue="0";

          if(id==="one")
              nextValue="1";

          if(id==="two")
              nextValue="2";
          if(id==="plus")
              nextValue="+";
          if(id==="three")
              nextValue="3";
          if(id==="four")
              nextValue="4";
          if(id==="five")
              nextValue="5";
          if(id==="minus")
              nextValue="-";
          if(id==="six")
              nextValue="6";
          if(id==="seven")
              nextValue="7";
          if(id==="eight")
              nextValue="8";
          if(id==="mul")
              nextValue="*";
          if(id==="nine")
              nextValue="9";
          if(id==="clear")
          {
              existingValue = "";
              nextValue="";
          }


          if(id==="divide") 
              nextValue="/";

          if(id==="equal") { // 4. only perform calculation when user wants it so on "=" perform calculation

            /*
                // 5
                assume input is -> "11-22+33" 
                then existingValue = 11-22+33
                operators will have value like ["", "-", "+", ""]
                here, split is function in which i had given regex 
                [0-9]+ means it will be splited with any between 0 to 9 so we will only get operators like: +, -, * and /

                // 6
                operators.slice
                operators = ["", "-", "+", ""] we got
                we no need leading and trailing "" so remove it, then i have only [-, +]

                // 7 
                similar to operators i had splitted using operators to fetch values
                values = ["11", "22", "33"]

                // 8
                in a while i have performed a calculation using following logic:

                values = ["11", "22", "33"]
                operators = ["-", "+"]

                  result  = values[0] operator[0] values[1]
                // -11    =   11          -          22

                now, values first two value replace with result value
                values = [-11, 33]

                and remove the first operator.
                operator = [+]

                this process we continue till I have only one value in values array, that value will result, that's at


                // point: 9
                validate function:
                this function used to check what value should be allowed after specific char.

                reg = ^([0-9]+[+\-\*\/]?
                this regex return false in case of user enters multiple operators etc..
                wrong input: 99+88+++ // this won't allow and i returned false

            */

              let operators = existingValue.split(/[0-9]+/gm); // 5
              operators = operators.slice(1, operators.length - 1); // 6. removing leading and trailing space

              let values = existingValue.split(/[+\-\*\/]+/gm); // 7.

              while (values.length != 1) {  // 8
                  let twoValues = values.slice(0, 2); 
                  values = values.slice(2, values.length); // removing first two value as we are calculating those twoValues

                  let op = operators[0];
                  operators = operators.slice(1,operators.length); // removing first operator as we are calculating using that operator

                  let result = 0;
                  switch(op) {
                      case "+":
                          result = parseInt(twoValues[0]) + parseInt(twoValues[1]);
                          break;
                      case "-":
                          result = parseInt(twoValues[0]) - parseInt(twoValues[1]);
                          break;
                      case "*":
                          result = parseInt(twoValues[0]) * parseInt(twoValues[1]);
                          break;
                      case "/":
                          result = parseInt(parseInt(twoValues[0]) / parseInt(twoValues[1]));
                          break;

                  }
                  values.splice(0,0, result); // adding result value at position 0

              }
              existingValue = ""
              nextValue = values[0];
          }

          let finalValue = existingValue + nextValue;
          let isValidValue = validate(finalValue);
          if (isValidValue) { // only append value if its validated
              document.getElementById("abcd").innerHTML = existingValue + nextValue;    
          }            
      }

      // this function which will validate on every button
      function validate(finalValue)  // 9
      {
      var regex = /^([0-9]+[+\-\*\/]?)*$/i;
      return regex.test(finalValue); // 
      }

   </script>
</html>

关于javascript - 如何在 javascript 计算器中检测和存储操作符前后的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59483835/

相关文章:

javascript - 组件无法正确更新 View

javascript - Angular 根据状态添加主体类

html - 如何在 Firefox 中获取外部链接的 SVG 剪辑路径

html - 如果文本达到 div 限制,则调整文本大小,然后在调整大小后保持居中

html - 边框导致DIV溢出

javascript - JQuery 中的精简

javascript - 更改 PHP 中禁用按钮的外观

html - 我必须在我的 CSS 中更改什么,以便当悬停在导航菜单上时,悬停不会像现在这样到处都是?

javascript - 如何将本地文本文件上传到文本区域(网页内)

jQuery Roundabout 重绘/调整大小问题