开发者

Dynamic JavaScript If Statement

In PHP I can do:

// $post = 10; $logic = >; $value = 100
$valid = eval("return ($post $logic $value) ? true : false;");

So t开发者_开发知识库he 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


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);


A little late, but you could've done the following:

var dynamicCompare = function(a, b, compare){
    //do lots of common stuff

    if (compare(a, b)){
        //do your thing
    } else {
        //do your other thing
    }
}

dynamicCompare(a, b, function(input1, input2){ return input1 < input2;}));
dynamicCompare(a, b, function(input1, input2){ return input1 > input2;}));
dynamicCompare(a, b, function(input1, input2){ return input1 === input2;}));


JavaScript have an eval function too: http://www.w3schools.com/jsref/jsref_eval.asp

eval("valid = ("+post+logic+value+");");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜