How to use a mathematical symbol as a variable for a mathematical operation in Javascript?
Works:
if(1 < 2) alert("yes");
Fails:
var sign = "<";
if(1 sign 2) alert("yes");
How to use a mathematical symbol as a variable for a mathematical operation in Javascript?
Works:
if(1 < 2) alert("yes");
Fails:
var sign = "<";
if(1 sign 2) alert("yes");
You can use eval:
if(eval('1' + sign + '2')) alert("yes");
But eval is frowned upon for many good reasons, so as an alternative, you could check the sign and perform the relevant test. For example:
if(test(1, 2, sign)) alert("yes");
function test(x, y, sign){
switch (sign) {
case "<":
return x < y;
case ">":
return x > y;
case "==":
return x == y;
// Add a case for each sign you wish to support
}
return false;
}