dot-notation
盡可能強制使用點號表示法
在 JavaScript 中,可以使用點號表示法 (foo.bar
) 或方括號表示法 (foo["bar"]
) 訪問屬性。然而,點號表示法通常更受歡迎,因為它更易於閱讀、更簡潔,並且更適用於積極的 JavaScript 壓縮器。
foo["bar"];
規則詳情
此規則旨在通過鼓勵盡可能使用點號表示法風格來維持程式碼一致性並提高程式碼可讀性。因此,當遇到不必要的方括號表示法使用時,它會發出警告。
此規則的錯誤程式碼範例
在 Playground 中開啟
/*eslint dot-notation: "error"*/
const x = foo[];
此規則的正確程式碼範例
在 Playground 中開啟
/*eslint dot-notation: "error"*/
const x = foo.bar;
const y = foo[bar]; // Property name is a variable, square-bracket notation required
選項
此規則接受單個選項參數
- 將
allowKeywords
選項設定為false
(預設為true
) 以遵循 ECMAScript 版本 3 相容風格,避免對保留字屬性使用點號表示法。 - 將
allowPattern
選項設定為正則表達式字串,以允許對符合模式的屬性名稱使用方括號表示法 (預設情況下,不測試任何模式)。
allowKeywords
{ "allowKeywords": false }
選項的正確程式碼範例
在 Playground 中開啟
/*eslint dot-notation: ["error", { "allowKeywords": false }]*/
const foo = { "class": "CS 101" }
const x = foo["class"]; // Property name is a reserved word, square-bracket notation required
{ "allowKeywords": false }
選項的額外正確程式碼範例
在 Playground 中開啟
/*eslint dot-notation: ["error", { "allowKeywords": false }]*/
class C {
#in;
foo() {
this.#in; // Dot notation is required for private identifiers
}
}
allowPattern
例如,當準備要發送到外部 API 的數據時,通常需要使用包含底線的屬性名稱。如果 camelcase
規則生效,則這些 snake case 屬性將不被允許。通過為 dot-notation
規則提供 allowPattern
,可以使用方括號表示法訪問這些 snake case 屬性。
{ "allowPattern": "^[a-z]+(_[a-z]+)+$" }
(用於查找 snake case 命名屬性的模式) 選項的錯誤程式碼範例
在 Playground 中開啟
/*eslint dot-notation: ["error", { "allowPattern": "^[a-z]+(_[a-z]+)+$" }]*/
const data = {};
data[] = 42;
{ "allowPattern": "^[a-z]+(_[a-z]+)+$" }
(用於查找 snake case 命名屬性的模式) 選項的正確程式碼範例
在 Playground 中開啟
/*eslint dot-notation: ["error", { "allowPattern": "^[a-z]+(_[a-z]+)+$" }]*/
const data = {};
data["foo_bar"] = 42;
版本
此規則在 ESLint v0.0.7 中引入。