JavaScript - 传递一个布尔(或按位)运算符作为参数?

问题描述 投票:0回答:4

在C#中有各种方法来执行此C# Pass bitwise operator as parameter特别是“Bitwise.Operator.OR”对象,但这样的事情可以在JavaScript中完成吗?例如:

function check(num1, num2, op) {
    return num1 op num2; //just an example of what the output should be like
}

check(1,2, >); //obviously this is a syntax error, but is there some kind of other object or bitwise operator of some kind I can plug into the place of ">" and change the source function somehow?
javascript bitwise-operators boolean-operations
4个回答
4
投票

您可以创建一个对象,其中键作为运算符,值作为函数。您将需要Bracket Notation来访问这些功能。

你可以使用Rest Parameters和some()以及every()&&||提供两个以上的参数。

对于按位运算符或+,-,*,/多个值,您可以使用reduce()

const check = {
  '>':(n1,n2) => n1 > n2,
  '<':(n1,n2) => n1 < n2,
  '&&':(...n) => n.every(Boolean),
  '||':(...n) => n.some(Boolean),
  '&':(...n) => n.slice(1).reduce((ac,a) => ac & a,n[0])
}

console.log(check['>'](4,6)) //false
console.log(check['<'](4,6)) /true
console.log(check['&&'](2 < 5, 8 < 10, 9 > 2)) //true

console.log(check['&'](5,6,7)  === (5 & 6 & 7))

1
投票

怎么样的:

 function binaryOperation( obj1, obj2, operation ) {
     return operation( obj1, obj2 );
 }
 function greaterThan( obj1, obj2 ) {
    return obj1 > obj2 ;
 }
 function lessThan( obj1, obj2 ) {
    return obj1 < obj2 ;
 }
 alert( binaryOperation( 10, 20, greaterThan ) );
 alert( binaryOperation( 10, 20, lessThan ) );

0
投票

您可以执行链接答案建议的完全相同的操作:

function check(num1, num2, op) {
  return op(num1, num2);
}

// Use it like this
check(3, 7, (x, y) => x > y);

您还可以创建一个提供所有这些操作的对象:

const Operators = {
  LOGICAL: {
    AND: (x, y) => x && y,
    OR: (x, y) => x || y,
    GT: (x, y) => x > y,
    // ... etc. ...
  },
  BITWISE: {
    AND: (x, y) => x & y,
    OR: (x, y) => x | y,
    XOR: (x, y) => x ^ y,
    // ... etc. ...
  }
};

// Use it like this
check(3, 5, Operators.BITWISE.AND);

0
投票

这不可能。但是你可以通过以下方式解决这个问题:

function evaluate(v1, v2, op) {
    let res = "" + v1 + op + v2;
    return eval(res)
}
console.log(evaluate(1, 2, "+"));
# outputs 3

但是在传递args时要小心,因为如果将一些hacky代码传递给函数,它们将被评估是危险的。

© www.soinside.com 2019 - 2024. All rights reserved.