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?
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?
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)) { .... } Source: https://ru.stackoverflow.com/questions/578912/
All Articles
evalthat there is a terrible evil and the answer is @tutankhamun. - user207618if (eval(`a ${symbol[0]} b`)) {- GrundyevalI didn’t think :) And yes, such anevalis really evil xD - Pavel Mayorov