Using Select Value As Operator
How can I use the select's value as operator for making some calculations?
Solution 1:
try something like this
var operators = {
'+': function(a, b) { return a + b },
'-': function(a, b) { return a - b },
'*': function(a, b) { return a * b },
'/': function(a, b) { return a / b }
};
var op = '+';
alert(operators[op](10, 20));
Solution 2:
Try eval
eval("x = A" + op + "B");
alert(x);
Solution 3:
You can use an object to map values to functions:
var operators = {
'+': function(x, y) { return x + y; },
'-': function(x, y) { return x - y; },
'*': function(x, y) { return x * y; },
'/': function(x, y) { return x / y; }
};
var result = operators[op](A, B);
Post a Comment for "Using Select Value As Operator"