no-else-return
在 if
陳述式中,當 if
區塊包含 return
陳述式時,不允許使用 else
區塊
如果 if
區塊包含 return
陳述式,則 else
區塊會變得不必要。其內容可以放在區塊之外。
function foo() {
if (x) {
return y;
} else {
return z;
}
}
規則詳細資訊
此規則旨在突顯在包含 return
陳述式的 if
後面,不必要的程式碼區塊。 因此,當它遇到跟在 if
鏈後面的 else
時,它會發出警告,所有 if
都包含 return
陳述式。
選項
此規則具有物件選項
allowElseIf: true
(預設) 允許在return
後面使用else if
區塊allowElseIf: false
不允許在return
後面使用else if
區塊
allowElseIf: true
此規則的不正確程式碼範例
在 Playground 中開啟
/*eslint no-else-return: "error"*/
function foo1() {
if (x) {
return y;
} else
}
function foo2() {
if (x) {
return y;
} else if (z) {
return w;
} else
}
function foo3() {
if (x) {
return y;
} else
return t;
}
function foo4() {
if (error) {
return 'It failed';
} else
}
// Two warnings for nested occurrences
function foo5() {
if (x) {
if (y) {
return y;
} else
} else
}
此規則的正確程式碼範例
在 Playground 中開啟
/*eslint no-else-return: "error"*/
function foo1() {
if (x) {
return y;
}
return z;
}
function foo2() {
if (x) {
return y;
} else if (z) {
var t = "foo";
} else {
return w;
}
}
function foo3() {
if (x) {
if (z) {
return y;
}
} else {
return z;
}
}
function foo4() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}
allowElseIf: false
此規則的不正確程式碼範例
在 Playground 中開啟
/*eslint no-else-return: ["error", {allowElseIf: false}]*/
function foo() {
if (error) {
return 'It failed';
} else
}
此規則的正確程式碼範例
在 Playground 中開啟
/*eslint no-else-return: ["error", {allowElseIf: false}]*/
function foo() {
if (error) {
return 'It failed';
}
if (loading) {
return "It's still loading";
}
}
版本
此規則在 ESLint v0.0.9 中引入。