有一种方法使比较运算符变量? [英] Is there a way to make a comparison operator a variable?

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

问题描述

类似于 python:使变量等于运算符(+,/ *, - )



我有一段代码,用户可以选择一种类型的比较运行, 。我很好奇,是否有任何方式在Javascript中将用户提供的比较值转换为实际的比较,让我做一些像:

  if(user_val user_comparison other_val){
do_something();
}

而不是像下面这样做:

  if(user_comparison ='<'){
if(user_val< other_val){
do_something
}
else if(user_comparison ='< ='){
if(user_val< = other_val){
do_something
}
.... etc

请注意,如果任何比较

解决方案

这是不可能的。但是你可以更好的结构你的代码。例如,您可以有一个查找表:

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

及更高版本:

  if(operator_table [user_comparison](user_val,other_val)){
// do something
}

当然,您还应该处理表中不存在 user_comparison 的情况。



这些也可以更好地控制允许和不允许的操作符。



这里是一个 DEMO 创建 @Jesse 。 p>

Similar to python: make a variable equal an operator (+,/,*,-)

I've got a bit of code where the user can pick a type of comparison to be run, and a value to compare against. I'm curious to know if there's any way in Javascript to turn that user provided comparison value into an actual comparison, allowing me to do something like:

if (user_val user_comparison other_val) {
    do_something();
}

Instead of having to do something like:

if (user_comparison = '<') {
    if (user_val < other_val) {
        do_something();
    }
else if (user_comparison = '<=') {
    if (user_val <= other_val) {
        do_something();
    }
....etc

Note that should any of the comparisons be matched, the same code will be executed.

解决方案

No that is not possible. But you can structure your code in a better way. For example you can have a lookup table:

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

and later:

if(operator_table[user_comparison](user_val, other_val)) {
    // do something
}

Of course you should also handle the case when user_comparison does not exist in the table.

These also gives you a better control over allowed and not allowed operators.

Here is a DEMO create by @Jesse.

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

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