簡體   English   中英

JavaScript中的匿名函數

[英]Anonymous function in condition in JavaScript

我想在if語句的條件下使用匿名函數

使用運行JS 1.5的Firefox 60.7.2.esr

我試過這樣的東西,認為它應該像forEach語句中的匿名函數一樣工作:

 if (function() { var b = true; if (b) { return true; } else { return false; } }) { //do something } 

我的實際匿名函數相當復雜,但原則上它應該以相同的方式工作。 問題似乎是匿名函數根本不運行。 有沒有辦法讓它運行?

你所做的就是在這里聲明一個函數,它實際上從未被調用過。 為什么不稍微清理代碼,並使其更具可讀性:

 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 
}

在這種情況下,您需要使用IIFE - 立即調用函數表達式

 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;} 

為了使它按預期工作,在匿名函數的定義周圍添加括號( ) ,然后在右括號之后,添加()以調用匿名函數:

 if ((function() { var b = true; if (b) { return true; } else { return false; } })()) { console.log('if passed'); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM