Javascript Variable Operators
Are these possible in Javascript? I've got something like this: var op1 = '<'; var op2 = '>'; if (x op1 xval && y op2 yval) { console.log('yay'); } Basically I nee
Solution 1:
That is not possible, but this is:
var operators =
{
'<': function(a, b) { return a < b; },
'>': function(a, b) { return a > b; },
/* ... etc. ... */
};
/* ... */var op1 = '<';
var op2 = '>';
if (operators[op1](a, b) && operators[op2](c, d))
{
/* ... */
}
Solution 2:
Not directly, but you can create a function like this:
if (operate(op1, x, xval) && operate(op2, x, xval)) {
console.log('yay');
}
function operate(operator, x, y) {
switch(operator) {
case'<':
return x < y;
}
}
Solution 3:
You could do something like this.
varOpMap = {
'>': function (a,b) return a>b;},
'<': function (a,b) return a<b;}
}
if (OpMap[op1](x,xval) && OpMap[op2](y,yval)) {
console.log('yay');
}
Solution 4:
It's not nice, but possible:
var op1 = "<";
var op2 = ">";
if (eval("x"+op1+xval+" && y"+op2+yval)) {
console.log('yay');
}
Also see my jsfiddle. I would prefer bobbymcr answer.
Post a Comment for "Javascript Variable Operators"