版本

max-depth

強制執行區塊可以巢狀的最大深度

許多開發人員認為,如果區塊巢狀超過一定的深度,程式碼會變得難以閱讀。

規則詳細資訊

此規則強制執行區塊可以巢狀的最大深度,以降低程式碼的複雜性。

選項

此規則具有數字或物件選項

  • "max"(預設值 4)強制執行區塊可以巢狀的最大深度

已過時: 物件屬性 maximum 已過時;請改用物件屬性 max

max

此規則使用預設 { "max": 4 } 選項的錯誤程式碼範例

在遊樂場中開啟
/*eslint max-depth: ["error", 4]*/

function foo() {
    for (;;) { // Nested 1 deep
        while (true) { // Nested 2 deep
            if (true) { // Nested 3 deep
                if (true) { // Nested 4 deep
                    if (true) { // Nested 5 deep
                    }
                }
            }
        }
    }
}

此規則使用預設 { "max": 4 } 選項的正確程式碼範例

在遊樂場中開啟
/*eslint max-depth: ["error", 4]*/

function foo() {
    for (;;) { // Nested 1 deep
        while (true) { // Nested 2 deep
            if (true) { // Nested 3 deep
                if (true) { // Nested 4 deep
                }
            }
        }
    }
}

請注意,類別靜態區塊不計為巢狀區塊,並且其中的深度與封閉的上下文分開計算。

此規則使用 { "max": 2 } 選項的錯誤程式碼範例

在遊樂場中開啟
/*eslint max-depth: ["error", 2]*/

function foo() {
    if (true) { // Nested 1 deep
        class C {
            static {
                if (true) { // Nested 1 deep
                    if (true) { // Nested 2 deep
                        if (true) { // Nested 3 deep
                        }
                    }
                }
            }
        }
    }
}

此規則使用 { "max": 2 } 選項的正確程式碼範例

在遊樂場中開啟
/*eslint max-depth: ["error", 2]*/

function foo() {
    if (true) { // Nested 1 deep
        class C {
            static {
                if (true) { // Nested 1 deep
                    if (true) { // Nested 2 deep
                    }
                }
            }
        }
    }
}

版本

此規則是在 ESLint v0.0.9 中引入的。

資源

變更語言