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

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -