var symbol = ['==', '>='] var a = 2 var b = 1 if (a symbol[0] b) { .... } 

How to write such code syntactically correct and working? It is necessary that the comparison sign be in a variable that will be overridden. Or is this not possible?

  • In JS, operators cannot be overloaded, especially since they are also retrieved from an array. Only eval that there is a terrible evil and the answer is @tutankhamun. - user207618
  • @PavelMayorov, why not help? if (eval(`a ${symbol[0]} b`)) { - Grundy
  • @Grundy yes, it will. Something about the easiest way to call eval I didn’t think :) And yes, such an eval is really evil xD - Pavel Mayorov
  • @PavelMayorov, well, how can I tell, if only my code, but there won't be much difference - Grundy

2 answers 2

Not take off. IMHO only use eval , but I would not. Alternatively, I would have made a hash of the comparison functions and substituted the arguments into the function selected by the key (as the key is an operation)

 var oper = { '==': function (a, b) { return a == b; }, '>=': function (a, b) { return a >= b; } }; var a = 2; var b = 1; var ix = '=='; if (oper[ix](a, b)) { .... } 

    tutankhamun I proposed to add comparison operations to the hash - but in some cases it is not at all possible to use their string form - but to use functions directly.

    Your code may look like this (I use arrow functions to simplify, note that they do not work in IE and Safari):

     var symbol = [ (a, b) => a == b, (a, b) => a >= b ] var a = 2 var b = 1 if (symbol[0](a, b)) { .... } 
    • one
      I would change the symbol to some comparers :-) - Grundy
    • Plus Grundy. In order not to spend cognitive efforts on understanding, what is the type of Symbol - Duck Learns to Take Cover
    • @Grundy variable name I took from the question - Pavel Mayorov
    • @ Duck ^^^^^^^^^^^^ Pavel Mayorov