Is there a way to make a variable comparison operator?

Similar to python: make a variable equal to the operator (+, /, *, -)

I have some code where the user can select the type of comparison to run and the value to compare. I am curious to know if there is any way in Javascript for this user to provide a comparative value in the actual comparison, which allows me to do something like:

if (user_val user_comparison other_val) {
    do_something();
}

Instead of doing something like:

if (user_comparison = '<') {
    if (user_val < other_val) {
        do_something();
    }
else if (user_comparison = '<=') {
    if (user_val <= other_val) {
        do_something();
    }
....etc

Note that when matching any of the comparisons, the same code will be executed.

+5
source share
3 answers

No, It is Immpossible. But you can better structure your code. For example, you can have a lookup table:

var operator_table = {
    '>': function(a, b) { return a > b; },
    '<': function(a, b) { return a < b; }
    // ...
};

and later:

if(operator_table[user_comparison](user_val, other_val)) {
    // do something
}

, , user_comparison .

.

DEMO @Jesse.

+10

, , , javascript, eval() .

eval() , JavaScript. , , JavaScript , eval() . , , , . , :

, .

, eval() JavaScript , . . , eval() , , eval() , , .

eval(), , , Felix Kling. , eval() , :

function compare(a, op, b)
{
  // Check that we have two numbers and an operator fed as a string.
  if (typeof a != 'number' || typeof b != 'number' || typeof op != 'string')
    return

  // Make sure that the string doesn't contain any executable code by checking
  // it against a whitelist of allowed comparison operators.
  if (['<', '>', '<=', '>=', '==', '!='].indexOf(op) == -1)
    return

  // If we have reached here, we are sure that a and b are two integers and
  // op contains a valid comparison operator. It is now safe to concatenate
  // them and make a JavaScript executable code.
  if (eval(a + op + b))
    doSomething();
}

, , . . https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#White_List_Input_Validation .

: http://jsfiddle.net/YrQ4C/ ( ):

function doSomething()
{
  alert('done something!')
}

function compare(a, op, b)
{
  if (typeof a != 'number' || typeof b != 'number' || typeof op != 'string')
    return

  if (['<', '>', '<=', '>=', '==', '!='].indexOf(op) == -1)
    return

  if (eval(a + op + b))
    doSomething();
}

// Positive test cases
compare(2, '<', 3)
compare(2, '<=', 3)

// Negative test cases
compare(2, '>', 3)
compare(2, '>=', 3)

// Attack tests
compare('alert(', '"attack!"', ')')

// Edit: Adding a new attack test case given by Jesse
// in the comments below. This function prevents this
// attack successfully because the whitelist validation
// for the second argument would fail.
compare(1, ';console.log("executed code");2==', 2)

: : http://jsfiddle.net/99eP2/

+4

Since @Susam Pal code is not working. I am publishing a working version

<html>
  <head>
   <script>
       function CompareSomething(val1, compareString, val2) {  
           eval('if(' + val1 + ' ' + compareString + ' ' + val2 + '){conditionPassed();}else{conditionFailed();}'); 
  }
  function compare(a, op, b) { 
      if (eval(a + op + b))
          conditionPassed();
      else
         conditionFailed();
  }
  function conditionPassed() {
      alert('condition passed');
  }
  function conditionFailed() {
      alert('condition failed');
  }
    </script>
  </head> 
<body>
a:<input id='txt1' type="text" />&nbsp;op:<input id='txt2' type="text" />&nbsp;b:<input id='txt3' type="text" /><br/>
<button id='compare'  onclick='CompareSomething(document.getElementById("txt1").value,document.getElementById("txt2").value,document.getElementById("txt3").value)'>Compare Esen Method</button><br/>
<button id='compare'  onclick='Compare(document.getElementById("txt1").value,document.getElementById("txt2").value,document.getElementById("txt3").value)'>Compare Susam Method</button>
  </body>
 </html>
-1
source

All Articles