变量运算符可能吗? [英] Are Variable Operators Possible?

查看:174
本文介绍了变量运算符可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做类似于以下任何一种情况:

Is there a way to do something similar to either of the following:

var1 = 10; var2 = 20;
var operator = "<";
console.log(var1 operator var2); // returns true

- 或 -

var1 = 10; var2 = 20;
var operator = "+";
total = var1 operator var2; // total === 30


推荐答案

不出来框。但是,很容易用包括JS在内的多种语言手工构建。

Not out of the box. However, it's easy to build by hand in many languages including JS.

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

var op = '+';
alert(operators[op](10, 20));

您可以使用基于ascii的名称,例如加上,如果你不需要,避免通过字符串。然而,有一半类似于这个问题的问题被问到了,因为有人用字符串表示操作符和想要的函数。

You can use ascii-based names like plus, to avoid going through strings if you don't need to. However, half of the questions similar to this one were asked because someone had strings representing operators and wanted functions from them.

这篇关于变量运算符可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆