var a = number; // тут у нас число var b = secondnumber; // тут у нас второе число var action = '+'; //действие допустим добавление var result = a + action + b; // сделаем пример 1 + 1 console.log(result); //результат выведет нам 1+1, а вместо этого нам нужно 2! 

How can you implement exactly the mathematical action and not just add the text together? The topic seems to be simple, but I cannot understand what the matter is, I will be grateful for your help!

  • in javascript there is a function eval that allows to execute arbitrary code. Without its use, just like in any other language: using the parsing of the expression, or as in the answer below, check the sign immediately and perform the corresponding function - Grundy

1 answer 1

Something like that

 var operation = { '+' : function( a, b ) { return a + b; } }; var a = number; // тут у нас число var b = secondnumber; // тут у нас второе число var action = '+'; //действие допустим добавление var result = operation[action]( a, b ); // сделаем пример 1 + 1 console.log(result); //результат выведет 2 

Here is an example of the page with the proposed solution.

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <h1>Test of operation plus</h1> <script> window.onload = function (firstNumber, secondNumber) { var operation = { "+": function (a, b) { return a + b; } }; var a = firstNumber; var b = secondNumber; var action = "+"; var result = operation[action](a, b); alert(result); }(1, 2); </script> </body> </html> 

In the alert displays the number 3 .

  • It works by itself, but for some reason it does not exist inside the function ( - arthru
  • That's what happened jsfiddle.net/y7vt5hpc but why does not work? - arthru
  • @arthru And what is this string "How much is * number * action * secondnumber": function (number, action, secondnumber) { - Vlad from Moscow
  • @arthru See my updated answer. - Vlad from Moscow
  • I just play around with voice commands, and I get it as a list of functions and therefore I need everything to happen inside the function - arthru