我想在if语句的情况下使用匿名函数
使用运行JS 1.5的Firefox 60.7.2.esr
我尝试了类似的方法,确定它应该像forEach语句中的匿名函数一样工作:
if (function() {
var b = true;
if (b) {
return true;
} else {
return false;
}
}) {
//do something
}
我实际的匿名功能要复杂得多,但是原则上它应该以相同的方式工作。问题似乎是匿名函数根本没有运行。有没有办法使其运行?
答案 0 :(得分:2)
您要做的只是在这里声明一个函数,实际上从未调用过它。为什么不清理一下代码,使其更具可读性呢?
const fn = function() {
var b = true;
if (b) {
return true;
} else {
return false;
}
};
if ( fn() ) {
//do something
console.log('fn() is true!')
}
最终,要调用您的函数,您需要使用()
并有选择地传递参数来调用该函数。如果要保留那里的丑陋混乱,只需将函数包装在()中,这样就不会出现语法错误,然后直接调用它:
if ( (function() {
var b = true;
if (b) {
return true;
} else {
return false;
}
})() ) {
//do something
}
答案 1 :(得分:1)
在这种情况下,您需要使用IIFE - Immediately Invoked Function Expression:
if ( (function(){ var b = true; if (b) { return true; } else { return false; } })() )
{
//do something
console.log("Doing something...");
}
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
但是,代码将很难阅读(IMO),最好这样做:
function checkForDoSomething()
{
var b = true;
if (b)
return true;
else
return false;
}
if ( checkForDoSomething() )
{
//do something
console.log("Doing something...");
}
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 2 :(得分:0)
要使此功能按预期工作,请在匿名函数的定义周围添加括号( )
,然后在结束括号之后添加()
以使匿名函数被调用:
if ((function() {
var b = true;
if (b) {
return true;
} else {
return false;
}
})()) {
console.log('if passed');
}