如何使用变量设置条件作为函数中的参数?
how to set a condition with a variable as a parameter in a function?
我做了一个函数,但我需要在特定情况下使用特定条件调用它,唯一的问题是我需要检查的变量在我创建的函数中。
这是我正在尝试做的一个例子:
//this works since nothing is out of scope
function thisWorks(condition) {
if (condition) {
console.log("works");
alert("works");
}
}
thisWorks(3 < 2);
//this wont work since the x var is out of scope
function howDoIDoThis(condition) {
let x = 3;
if (condition) {
console.log("i dont know how to do this");
}
}
howDoIDoThis(x === 3);
有什么方法可以引用 x 变量吗?我知道在这个例子中我可以很容易地将 x 移出,但对于我实际想要做的事情,x 需要留在函数内
您不应该关心另一个函数中变量的名称。
相反,传递一个接收变量作为参数的回调函数,并计算条件。
function howDoIDoThis(condition_function) {
let x = 3;
if (condition_function(x)) {
console.log("The condition is true");
} else {
console.log("The condition is false");
}
}
howDoIDoThis(n => n == 3);
howDoIDoThis(z => z == 2);
我做了一个函数,但我需要在特定情况下使用特定条件调用它,唯一的问题是我需要检查的变量在我创建的函数中。
这是我正在尝试做的一个例子:
//this works since nothing is out of scope
function thisWorks(condition) {
if (condition) {
console.log("works");
alert("works");
}
}
thisWorks(3 < 2);
//this wont work since the x var is out of scope
function howDoIDoThis(condition) {
let x = 3;
if (condition) {
console.log("i dont know how to do this");
}
}
howDoIDoThis(x === 3);
有什么方法可以引用 x 变量吗?我知道在这个例子中我可以很容易地将 x 移出,但对于我实际想要做的事情,x 需要留在函数内
您不应该关心另一个函数中变量的名称。
相反,传递一个接收变量作为参数的回调函数,并计算条件。
function howDoIDoThis(condition_function) {
let x = 3;
if (condition_function(x)) {
console.log("The condition is true");
} else {
console.log("The condition is false");
}
}
howDoIDoThis(n => n == 3);
howDoIDoThis(z => z == 2);