I want to calculate two numbers and its pretty simple.
But Is there any way to take operator in variable and then do the calculation?
var x = 5;
var y = 5;
var p = '+';
var z = x + p + y;
$(".button").click(function() {
alert(z);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>
A - The plus sign (+) is automatically overloaded in Java. The plus sign can be used to perform arithmetic addition. It can also be used to concatenate strings. However, the plus sign does more than concatenate strings.
The plus sign (+) is a string concatenation operator that permits us to thread together literals and variables into a single string.
The plus(+) sign before the variables defines that the variable you are going to use is a number variable.
A unary mathematical expression consists of only one component or element, and in Python the plus and minus signs can be used as a single element paired with a value to return the value's identity ( + ), or change the sign of the value ( - ). With a negative value the plus sign returns the same negative value.
Avoid eval
whenever possible. For this example, a simple switch...case
statement will be sufficient:
var x = 5;
var y = 5;
var z;
var p = "+";
switch (p) {
case "+":
z = x + y;
break;
case "-":
z = x - y;
break;
}
You can also use a map of functions:
var fnlist = {
"+": function(a, b) { return a + b; },
"-": function(a, b) { return a - b; }
}
var x = 5;
var y = 5;
var p = "+";
var z = fnlist[p](x, y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With