In PHP I can do:
// $post = 10; $logic = >; $value = 100
$valid = eval("return ($post $logic $value) ? true : false;");
So the statement above would return false.
Can I do something similar in JavaScript? Thanks!
Darren.
In PHP I can do:
// $post = 10; $logic = >; $value = 100
$valid = eval("return ($post $logic $value) ? true : false;");
So the statement above would return false.
Can I do something similar in JavaScript? Thanks!
Darren.
JavaScript have an eval function too: http://www.w3schools.com/jsref/jsref_eval.asp
eval("valid = ("+post+logic+value+");");
yes, there's eval
in javascript as well. for most uses it's not considered very good practice to use it, but i can't imagine it is in php either.
var post = 10, logic = '>', value = 100;
var valid = eval(post + logic + value);
If you want to avoid eval
, and since there are only 8 comparison operators in JavaScript, is fairly simple to write a small function, without using eval
at all:
function compare(post, operator, value) {
switch (operator) {
case '>': return post > value;
case '<': return post < value;
case '>=': return post >= value;
case '<=': return post <= value;
case '==': return post == value;
case '!=': return post != value;
case '===': return post === value;
case '!==': return post !== value;
}
}
//...
compare(5, '<', 10); // true
compare(100, '>', 10); // true
compare('foo', '!=', 'bar'); // true
compare('5', '===', 5); // false