I wish to use the Function
javascript feature instead of "eval", for implementing the ability to use comparison operators inside a filtering input field.
function test(){
let x = 5, y = 10, operator = '>';
return Function("return x" operator "y")(x, y);
}
console.log(test());
The code above throws an error, x, y appear undefined in the Function.
So how can I pass external variables to Function?
CodePudding user response:
Each parameter referenced in the function body should be a leading argument to the function, in string format.
function test(){
let x = 5, y = 10;
return Function('x', 'y', "return x>y")(x, y);
}
console.log(test());