javascript - Are Variable Operators Possible? -
is there way similar either of following:
var1 = 10; var2 = 20; var operator = "<"; console.log(var1 operator var2); // returns true
-- or --
var1 = 10; var2 = 20; var operator = "+"; total = var1 operator var2; // total === 30
not out of box. however, it's easy build hand in many languages including js.
var operators = { '+': function(a, b) { return + b }, '<': function(a, b) { return < b }, // ... }; var op = '+'; alert(operators[op](10, 20));
you can use ascii-based names plus
, avoid going through strings if don't need to. however, half of questions similar 1 asked because had strings representing operators , wanted functions them.
Comments
Post a Comment