开发者

Math operation when operator is stored in a string

开发者 https://www.devze.com 2023-02-15 20:33 出处:网络
Have two variables both containing integers: var input; var value; Need to perform arit开发者_如何转开发hmetic on them but have operator stored in variable:

Have two variables both containing integers:

var input;
var value;

Need to perform arit开发者_如何转开发hmetic on them but have operator stored in variable:

var operator;

How do i perform the math?

i.e. document.write(input operator value);

Thank You


switch (operator) {
  case '+': result = input + value; break;
  case '-': result = input - value; break;

etc.

}


For general purpose operators, you could define your operators like that:

var operators = {
    "+": function(a, b) { return a + b; },
    "x": function(a, b) { /* return cross product of a, b */ }
    /* etc */
};

var operator = '+';

var c = operators[operator](1, 2);  // c=3

In this way the operators object can be extended at runtime (even by the user if you like).


Security disclaimer : this is extremely unsafe and requires validating input before doing it. You should use one of the answers above for your use case, this is just for your information.

Still, it works:

eval("2" + op + "2")

A complete example here


I think this is the good way to take values or operators from user. And you can perform any operation on values. Because this the more flexible and easy to use.

var a = 10, b = 20, op = '+',
 ans = eval(`${a} ${op} ${b}`);
console.log(ans);

More example using prompt to get user input and alert to give answer

function select(num1, num2, selection) {
  return eval(`${Number(num1)} ${selection} ${Number(num2)}`);
}

const selection = prompt(` 
Enter operator:
multiply => *
exponent => **
divide => /
modulus => %
add => +
substract => -
`);

const num1 = prompt(`Enter first number`);
const num2 = prompt(`Enter second number`);

const result = select(num1, num2, selection);
alert(`The result is ${result}`);


yes you can make whole calculator using eval() function

0

精彩评论

暂无评论...
验证码 换一张
取 消