2010-01-11 44 views
1

在PHP中我可以這樣做:動態JavaScript的聲明如果

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

所以上面的語句將返回false。

我可以在JavaScript中做類似的事嗎?謝謝!

Darren。

+1

你爲什麼要這樣做? – James

+1

另外,'$ post $ logic $ value'返回一個布爾值,所以不需要'? true:false' ... – James

回答

6

是的,有在javascript eval爲好。對於大多數用途來說,使用它並不被認爲是很好的做法,但我無法想象它是在PHP中。

var post = 10, logic = '>', value = 100; 
var valid = eval(post + logic + value); 
+0

注意:這是不安全的。 –

16

如果你想避免eval,並且因爲只有8 comparison operators在JavaScript中,是相當簡單寫一個小功能,而無需使用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 
+0

我喜歡編碼的無限可能性。酷縮短者。 – scaryguy

1

有點晚了,但你可以做到以下幾點:

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