问题
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?
回答1:
You can create a object with keys as operators and values as functions. You will need Bracket Notation to access the functions.
You can use Rest Parameters and some()
and every()
for more than two parameters for &&
,||
.
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))
回答2:
How about something like:
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 ) );
回答3:
You can do the exact same thing suggested by the linked answers:
function check(num1, num2, op) {
return op(num1, num2);
}
// Use it like this
check(3, 7, (x, y) => x > y);
You can also create an object that provides all of these operations:
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);
回答4:
It is not possible. But 1 way you can approach this is by doing the following:
function evaluate(v1, v2, op) {
let res = "" + v1 + op + v2;
return eval(res)
}
console.log(evaluate(1, 2, "+"));
# outputs 3
But be careful while passing args
as they will be evaluated which is dangerous if some hacky code is passed to the function.
来源:https://stackoverflow.com/questions/55896390/javascript-pass-a-boolean-or-bitwise-operator-as-an-argument