Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 791
Twix Avatar asked Apr 14 '15 08:04

Twix


People also ask

What is the plus (+) sign used to do in Java?

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.

What data type is a plus sign?

The plus sign (+) is a string concatenation operator that permits us to thread together literals and variables into a single string.

What is the purpose of a plus symbol before a variable?

The plus(+) sign before the variables defines that the variable you are going to use is a number variable.

How do you use the plus sign in Python?

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.


1 Answers

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);
like image 71
Salman A Avatar answered Oct 02 '22 15:10

Salman A