This question has already been answered:

How to make it so that the variable Z displays the result of mathematical operations, and not just a string.

Here is the code:

var z = 0; var operat = ['+', '-']; var rand1 = operat[Math.floor(Math.random() * operat.length)]; var rand2 = operat[Math.floor(Math.random() * operat.length)]; var reZ1 = Math.floor(Math.random() * (10 - 1 + 1)) + 1; var reZ2 = Math.floor(Math.random() * (10 - 1 + 1)) + 1; console.log(reZ1, reZ2); z = z + rand1 + reZ1 + rand2 + reZ2; console.log(z); 

Reported as a duplicate by participants Alexey Shimansky , Grundy javascript Jan 7 '18 at 15:29 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    There are two options. The first option is eval() , the second is mathematics. The first option is not the best in terms of security, but convenient (for the developer).

    Here is an example of how to solve this problem with the help of mathematics:

     var z = 0; var operat = [1, -1]; var rand1 = operat[Math.floor(Math.random() * operat.length)]; var rand2 = operat[Math.floor(Math.random() * operat.length)]; var reZ1 = Math.floor(Math.random() * (10 - 1 + 1)) + 1; var reZ2 = Math.floor(Math.random() * (10 - 1 + 1)) + 1; console.log(reZ1, reZ2); z = z + rand1 * reZ1 + rand2 * reZ2; console.log(z); 

    OR

     function rand(min, max){ return Math.floor(Math.random() * (max-min + 1)) + min; } var z = 0, rand1 = Math.random()<0.5?-1:1; rand2 = Math.random()<0.5?-1:1; reZ1 = rand(10,1)*rand1, reZ2 = rand(10,1)*rand2; console.log(reZ1, reZ2); z = z + reZ1 + reZ2; console.log(z); 
    • Thank. A good option, also suitable! - Nikolay Kravtsov

    can use Eval()

     var z = 0; var operat = ['+', '-']; var rand1 = operat[Math.floor(Math.random() * operat.length)]; var rand2 = operat[Math.floor(Math.random() * operat.length)]; var reZ1 = Math.floor(Math.random() * (10 - 1 + 1)) + 1; var reZ2 = Math.floor(Math.random() * (10 - 1 + 1)) + 1; console.log("z =", z + rand1 + reZ1 + rand2 + reZ2); z += eval(rand1 + reZ1 + rand2 + reZ2); console.log(z); 

    but in order to cut off the "pampering" of users at the input of Eval() it is better to actually submit the result of a regular expression, in your case these are the numbers \d and +-
    as an example, the code left, it works
    but for more close to life tasks, it is recommended to replace the line with:
    z += eval((rand1 + reZ1 + rand2 + reZ2).match(/^[\d+-]*/g));
    or faster alternatives

    • Thanks, helped! Happy New Year! - Nikolay Kravtsov