2
a = Math.random();
b= Math.random();

az = Math.round(a);
bz = Math.round(b);

var chooseoperator = ['+','-','*','/'];


var operator = chooseoperator[Math.floor(Math.random() *chooseoperator.length)];

var final=az+operator+bz;

alert(final);

So the computer alerts,"1-0" or something similar. How can I make the computer solve it?

Stardust
  • 999
  • 3
  • 12
  • 24
  • Try [eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) – j08691 Sep 27 '15 at 22:26

2 Answers2

5

You should use eval:

alert(eval(final));
Buzinas
  • 11,597
  • 2
  • 36
  • 58
  • Thanks, I will definitely use your answer... I found an alternate version: [View Code](https://jsfiddle.net/alaskamani15/89xqwk85/8/) – Stardust Sep 27 '15 at 22:51
  • @AlaskaMani Cool workaround :) – Buzinas Sep 27 '15 at 22:52
  • You *should not* use eval unless you have absolutely no other option. – Salman A Sep 28 '15 at 07:19
  • 1
    @SalmanA that's bullshit. `eval` was design exactly to `evaluate` stuff, and dynamic Math is one of the best scenarios where you should use it. The famous '*eval is evil*' phrase is because people were using it for things they should never do. And worse than that, using it to parse untrusted source. – Buzinas Sep 28 '15 at 11:58
3

If you do not want to use eval because it runs the whole parser for such simple task you can use a simple switch.

BTW: final is a reserved word, do not use it as a variable name.

a = Math.random();
b = Math.random();

az = Math.round(a);
// to avoid division by zero
bz = Math.round(b) + 1;

var chooseoperator = ['+','-','*','/'];

var operator = chooseoperator[Math.floor(Math.random() *chooseoperator.length)];

var Final=az+operator+bz;

alert(Final);

var result;
switch(operator){
  case '+' : result = az + bz;
             break;
  case '-' : result = az - bz;
             break;
  case '*' : result = az * bz;
             break;

  case '/' : result = az / bz;
  // if you do not want the addition of 1 above
  // check the result for "Infinity" and(!) "NaN" here, e.g.:
  //         if(Math.abs(result) === Infinity || isNaN(result)){
  //           alert("Division by zero")
  //         }
  // "isNaN" checks for "0/0" and "Infinity" checks for x/0
             break;
  default: alert("something unexpected happend");
             break;
}
// the result is now in the aptly named variable "result"
alert("result = " + result);

Oh, I am too slow, it seems.

deamentiaemundi
  • 5,502
  • 2
  • 12
  • 20