nonblock-statement-body-position
強制單行陳述式的位置
此規則報告的某些問題可透過 --fix
命令列選項自動修正
此規則在 ESLint v8.53.0 中已棄用。請使用 @stylistic/eslint-plugin-js
中對應的規則。
在撰寫 if
、else
、while
、do-while
和 for
陳述式時,主體可以是單一陳述式而不是區塊。強制這些單一陳述式的一致位置可能會很有用。
例如,有些開發人員會避免撰寫如下程式碼
if (foo)
bar();
如果另一位開發人員嘗試將 baz();
新增至 if
陳述式,他們可能會錯誤地將程式碼變更為
if (foo)
bar();
baz(); // this line is not in the `if` statement!
為了避免此問題,可以要求所有單行 if
陳述式直接出現在條件之後,且沒有換行符號
if (foo) bar();
規則詳情
此規則旨在強制單行陳述式的一致位置。
請注意,此規則通常不會強制使用單行陳述式。如果您想要禁止單行陳述式,請改用 curly
規則。
選項
此規則接受字串選項
"beside"
(預設)禁止在單行陳述式之前出現換行符號。"below"
要求在單行陳述式之前出現換行符號。"any"
不強制單行陳述式的位置。
此外,該規則接受具有 "overrides"
鍵的可選物件選項。這可用於指定覆寫預設值的特定陳述式的位置。例如
"beside", { "overrides": { "while": "below" } }
要求所有單行陳述式都出現在與其父系相同的行上,除非父系是while
陳述式,在這種情況下,單行陳述式不得與同一行。"below", { "overrides": { "do": "any" } }
禁止所有單行陳述式出現在與其父系相同的行上,除非父系是do-while
陳述式,在這種情況下,不強制執行單行陳述式的位置。
使用預設 "beside"
選項時,此規則的不正確程式碼範例
/* eslint nonblock-statement-body-position: ["error", "beside"] */
if (foo)
else
while (foo)
for (let i = 1; i < foo; i++)
do
while (foo)
使用預設 "beside"
選項時,此規則的正確程式碼範例
/* eslint nonblock-statement-body-position: ["error", "beside"] */
if (foo) bar();
else baz();
while (foo) bar();
for (let i = 1; i < foo; i++) bar();
do bar(); while (foo)
if (foo) { // block statements are always allowed with this rule
bar();
} else {
baz();
}
使用 "below"
選項時,此規則的不正確程式碼範例
/* eslint nonblock-statement-body-position: ["error", "below"] */
if (foo)
else
while (foo)
for (let i = 1; i < foo; i++)
do while (foo)
使用 "below"
選項時,此規則的正確程式碼範例
/* eslint nonblock-statement-body-position: ["error", "below"] */
if (foo)
bar();
else
baz();
while (foo)
bar();
for (let i = 1; i < foo; i++)
bar();
do
bar();
while (foo)
if (foo) {
// Although the second `if` statement is on the same line as the `else`, this is a very common
// pattern, so it's not checked by this rule.
} else if (bar) {
}
使用 "beside", { "overrides": { "while": "below" } }
規則時,此規則的不正確程式碼範例
/* eslint nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] */
if (foo)
while (foo)
使用 "beside", { "overrides": { "while": "below" } }
規則時,此規則的正確程式碼範例
/* eslint nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] */
if (foo) bar();
while (foo)
bar();
何時不使用它
如果您不關心單行陳述式的一致位置,則不應開啟此規則。如果您使用 curly
規則的 "all"
選項,您也可以停用此規則,因為這將完全禁止單行陳述式。
版本
此規則在 ESLint v3.17.0 中引入。