How To Take Plus Sign In Variable
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?
Solution 1:
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);
Solution 2:
Or use parseInt on the string which you will be adding the variable to:
var x = 5;
var y = 5;
var p = '-';
var z = x + parseInt(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>
Solution 3:
You are looking for eval function:
var x = 5;
var y = 5;
var p = '+';
var z = x + p + y;
$(".button").click(function(){
alert(eval(z));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>
However, you have to remember that using eval
function is potentially risky. For example, if used in the wrong way it can allow one to make injection attacks. Debugging can be also more difficult. I suggest to read this question.
Solution 4:
you can use the eval
function:
var x = 5;
var y = 5;
var p = '+';
var z = eval(x + p + y);
alert(z);
Post a Comment for "How To Take Plus Sign In Variable"