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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With