iam*_*all 4 javascript logic eval dynamic
在PHP中,我可以这样做:
// $post = 10; $logic = >; $value = 100
$valid = eval("return ($post $logic $value) ? true : false;");
Run Code Online (Sandbox Code Playgroud)
所以上面的陈述将返回false.
我可以在JavaScript中做类似的事情吗?谢谢!
达伦.
CMS*_*CMS 22
如果你想避免eval,并且由于JavaScript 中只有8个比较运算符,编写一个小函数相当简单,完全没有使用eval:
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
Run Code Online (Sandbox Code Playgroud)
是的,这里也有evaljavascript.对于大多数用途来说,使用它并不是一个很好的做法,但我无法想象它也在PHP中.
var post = 10, logic = '>', value = 100;
var valid = eval(post + logic + value);
Run Code Online (Sandbox Code Playgroud)