blu*_*yke 1 javascript bitwise-operators boolean-operations
在 C# 中,有多种方法可以将C# Pass 按位运算符作为参数,特别是“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?
Run Code Online (Sandbox Code Playgroud)
您可以使用键作为运算符和值作为函数来创建对象。您将需要括号符号来访问这些功能。
对于, 的两个以上参数,您可以使用 Rest Parameters andsome()
和。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))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
536 次 |
最近记录: |