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?

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>

Answers:

Answer

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);
Answer

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>

Answer

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.

Answer

you can use the eval function:

var x = 5;
var y = 5;
var p = '+';
var z = eval(x + p + y);

alert(z);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.