Trying to make a calculator. It works as follows:
When you click on a number, it fits into the variable. When you click on the sign (+, -, *, /), they are added to the same variable as the digit. The result is for example:
var x = '18 * 2 + 3 '
I want to make it so that when you click on the equal sign, the equation located in the variable x has been solved, as for example, if it were just:
var x = 18 * 2 + 3.
console.log (x);
I tried the Number function and realized that I was doing something wrong.

Can you please tell me in what ways you can solve the problem and how can you automatically increase the height of the diva ('.example') when a certain number of characters are reached?

$(function() { var numbers = 0; var example = 0; // Пот нажатии на кнопку с цифро, он появляется в нижнем "табло" калькулятора $('.numBtn').click(function() { if (numbers.length >= 12) { return; } else { if (numbers == 0) { numbers = this.value; } else { numbers += this.value; } } $('.calcIn').text(numbers); }) // При нажатии на знак +, - , * или /, цифра и нажатый знак урованения добавляются в переменную example. $('.funcBtn').click(function(){ example += ($('.calcIn').text()) $('.desk').text(example+=this.value); numbers = 0 $('.calcIn').text(numbers) }) /*При нажатии на кнопку равно, результат примера находящегося в качестве строки в переменной example должен появиться в качестве текста в классе calcIn */ $('.equalBtn').click(function(){ // // $('.calcIn').text(result); }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <div class="simpleCalc"> <div class="scoreboard"> <div class="desk"> 0</div> <div class="calcIn" id="text">0</div> </div> <table> <input type="button" class="button bigButtonC cButton" value="C"> <input type="button" class="button topBtn CEbtn" value="CE"> <input type="button" class="button topBtn funcBtn" value="x2"> <input type="button" class="button topBtn funcBtn" value="del"> <input type="button" class="button topBtn funcBtn" value="÷"> <input type="button" class="button secLineBtn numBtn" value="7"> <input type="button" class="button secLineBtn numBtn" value="8"> <input type="button" class="button secLineBtn numBtn" value="9"> <input type="button" class="button secLineBtn funcBtn" value="×"> <br> <input type="button" class="button thirdLineBtn funcBtn" value="%"> <input type="button" class="button thirdLineBtn numBtn" value="4"> <input type="button" class="button thirdLineBtn numBtn" value="5"> <input type="button" class="button thirdLineBtn numBtn" value="6"> <input type="button" class="button thirdLineBtn funcBtn" value="−"> <input type="button" class="button fourthLineBtn funcBtn" value="√"> <input type="button" class="button fourthLineBtn numBtn" value="1"> <input type="button" class="button fourthLineBtn numBtn" value="2"> <input type="button" class="button fourthLineBtn numBtn" value="3"> <input type="button" class="button bigButtonPlus funcBtn" value="+"> <input type="button" class="button bottomLineBtn funcBtn" value="±"> <input type="button" class="button bottomLineBtn commaBtn" value=","> <input type="button" class="button bottomLineBtn numBtn" value="0"> <input type="button" class="button bottomLineBtn equalBtn" value="="> </table> </div> 

  • Run a string can eval , but - eval is evil . It is better to have a pool, where to throw the data of the form: [{type: 'number', value: 2}, {type: 'sign', value: '+'}, {type: 'number', value: 2}] . And by the button "Decide" to go through the array by the executer. - user207618
  • This is not an equation - Alex78191

3 answers 3

Good day! In your case, the use of the eval () function is suitable, although its use is not recommended in the community. It creates a full-fledged expression from the string for execution. For ease of demonstration, I changed your div to text input (the only difference in the code is that the input should not be named .text (), but val ()).

 $('.equalBtn').click(function() { let equation = $('.desk').val(); let result = eval(equation); $('.calcIn').text(result); }); 

About the height. The height of the elements itself is easily adjusted with the help of css, it is enough to set the width for the block element. In your case, if the answer is too long and in one "word", then you should use the overflow-wrap property, which solves this problem.

 #text { width: 200px; overflow-wrap: break-word; } 

For the demonstration, I added a button with the display of pi.

Demo: https://jsfiddle.net/w96k/regbLvbf/1/

  • Sense to copy someone else's answers? - user207618
  • Excuse me, where did I copy yours? Or are you accusing me of copying js funds? - w96k
  • About two already mentioned eval , you have not proposed anything conceptually new, which leads to the conclusion - copy-paste. - user207618
  • 2
    No one has provided a demo. No one answered the transfer question. In any case, I do not see anything wrong in several answers. - w96k

The eval () function evaluates javascript code.

And to increase the size of the element, it's the usual if:

 if (символов_достаточно) element.style.height = '20px'; //например (или методами jquery) 

BUT!

eval () is a dangerous function , it passed with the privileges of the caller. If you’re running away from your webpage / extension. More importantly, it was invoked, which was not susceptible.

eval () is the js interpreter, it has been the js interpreter that has been optimized by modern JS engines.

It is more correct (but not simpler) to write your own function (s), which parses the string into tokens and operates with <numbers> and <expressions>, correctly determines the order of calculations.

More information can be found on the request " lexical analyzer " in search engines and in books on building compilers.

  • Well, you have bent :) Why analyzers and, especially, compilers, if the author can change the structure and analyze nothing? - user207618
  • The author wanted to calculate the expression in the string :) What you suggested was a change in the architecture of his application :) I tried to answer the question. Teaching how it would be better not to plan, besides, it is much more interesting to learn from your mistakes;) - n3r0bi0m4n
  • Then you offered a venomous crutch, which is sure to [hurt, because the base] comes around with a slight expansion; it’s better to rewrite immediately, especially since nothing else has been done. - user207618
  • This crutch can become for a person a library for parsing arithmetic strings, in which he can add, for example, brackets or variables. Again, I tried to answer the question of how to calculate an expression from a string. If you change the logic, yes, you can split () a line in the desired order, you can immediately write the type and value of the lexeme, as you suggested. But you never know what you can think of: programming is a creative lesson :) - n3r0bi0m4n
  • That's the difference between good answers from mechanical ones: a good one will not only answer, but also share experience / knowledge as it should, so that, figuratively speaking, give a fishing rod, not a fish - user207618

There is a mathjs library

You can execute expressions in it:

 math.eval('sqrt(3^2 + 4^2)') // 5 math.eval('sqrt(-4)') // 2i math.eval('2 inch to cm') // 5.08 cm math.eval('cos(45 deg)') // 0.7071067811865476 

Sandbox where you can try