dot-notation
尽可能使用点符号
在 JavaScript 中,可以使用点表示法(foo.bar)或方括号表示法(foo["bar"])来访问属性。然而,通常更倾向于使用点表示法,因为它更易读、冗余更少,并且在使用激进的 JavaScript 压缩工具时效果更好。
🌐 In JavaScript, one can access properties using the dot notation (foo.bar) or square-bracket notation (foo["bar"]). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers.
foo["bar"];
规则详情
🌐 Rule Details
该规则旨在通过鼓励尽可能使用点表示法来保持代码一致性并提高代码可读性。因此,当遇到不必要的方括号表示法使用时,它会发出警告。
🌐 This rule is aimed at maintaining code consistency and improving code readability by encouraging use of the dot notation style whenever possible. As such, it will warn when it encounters an unnecessary use of square-bracket notation.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint dot-notation: "error"*/
const x = foo["bar"];
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint dot-notation: "error"*/
const x = foo.bar;
const y = foo[bar]; // Property name is a variable, square-bracket notation required
选项
🌐 Options
此规则接受单个选项参数:
🌐 This rule accepts a single options argument:
- 将
allowKeywords选项设置为false(默认值是true)以遵循 ECMAScript 版本 3 兼容的风格,避免对保留字属性使用点表示法。 - 将
allowPattern选项设置为一个正则表达式字符串,以允许对匹配特定模式的属性名称使用括号表示法(默认情况下,不测试任何模式)。
allowKeywords
适用于 { "allowKeywords": false } 选项的正确代码示例:
🌐 Examples of correct code for the { "allowKeywords": false } option:
/*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 } 选项的其他 正确 代码示例:
🌐 Examples of additional correct code for the { "allowKeywords": false } option:
/*eslint dot-notation: ["error", { "allowKeywords": false }]*/
class C {
#in;
foo() {
this.#in; // Dot notation is required for private identifiers
}
}
allowPattern
例如,当准备发送到外部 API 的数据时,通常需要使用包含下划线的属性名。如果 camelcase 规则生效,这些 蛇形命名 的属性将不被允许。通过向 dot-notation 规则提供 allowPattern,可以使用括号表示法访问这些蛇形命名的属性。
🌐 For example, when preparing data to be sent to an external API, it is often required to use property names that include underscores. If the camelcase rule is in effect, these snake case properties would not be allowed. By providing an allowPattern to the dot-notation rule, these snake case properties can be accessed with bracket notation.
示例 { "allowPattern": "^[a-z]+(_[a-z]+)+$" }(用于查找蛇形命名属性的模式)选项的错误代码示例:
🌐 Examples of incorrect code for the sample { "allowPattern": "^[a-z]+(_[a-z]+)+$" } (pattern to find snake case named properties) option:
/*eslint dot-notation: ["error", { "allowPattern": "^[a-z]+(_[a-z]+)+$" }]*/
const data = {};
data["fooBar"] = 42;
Examples of correct code for the sample { "allowPattern": "^[a-z]+(_[a-z]+)+$" } (pattern to find snake case named properties) option:
/*eslint dot-notation: ["error", { "allowPattern": "^[a-z]+(_[a-z]+)+$" }]*/
const data = {};
data["foo_bar"] = 42;
版本
此规则是在 ESLint v0.0.7 中引入。