本文介绍了JavaScript-将布尔(或按位)运算符作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,有多种方法可以执行此操作 C#将按位运算符作为参数传递专门用于"Bitwise.Operator.OR"对象,但是可以在JavaScript中完成类似的事情吗?例如:

In C# there are various ways to do this C# Pass bitwise operator as parameter specifically the "Bitwise.Operator.OR" object, but can something like this be done in JavaScript? For example:

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?

推荐答案

您可以使用键作为运算符,将值作为函数来创建对象.您需要使用括号表示法才能访问这些功能.

You can create a object with keys as operators and values as functions. You will need Bracket Notation to access the functions.

对于&& || .

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

For the bitwise operator or +,-,*,/ multiple values you can use 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))

这篇关于JavaScript-将布尔(或按位)运算符作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:54