no-useless-computed-key
禁止在物件和類別中使用不必要的計算屬性鍵
🔧 可修正
此規則報告的一些問題可以使用 --fix
命令列選項自動修正
對於像這樣的文字使用計算屬性是不必要的
var foo = {["a"]: "b"};
程式碼可以改寫為
var foo = {"a": "b"};
規則細節
此規則禁止不必要地使用計算屬性鍵。
此規則的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-useless-computed-key: "error"*/
var a = { };
var a = { };
var a = { };
var a = { };
var a = { };
var { } = obj;
var { } = obj;
class Foo {
}
此規則的正確程式碼範例
在遊樂場中開啟
/*eslint no-useless-computed-key: "error"*/
var c = { 'a': 0 };
var c = { 0: 0 };
var a = { x() {} };
var c = { a: 0 };
var c = { '0+1,234': 0 };
var { 0: a } = obj;
var { 'x': a } = obj;
class Foo {
"foo" = "bar";
0() {}
'a'() {}
get 'b'() {}
set 'c'(value) {}
static "foo" = "bar";
static 'a'() {}
}
此規則額外的正確程式碼範例
在遊樂場中開啟
/*eslint no-useless-computed-key: "error"*/
var c = {
"__proto__": foo, // defines object's prototype
["__proto__"]: bar // defines a property named "__proto__"
};
class Foo {
["constructor"]; // instance field named "constructor"
"constructor"() {} // the constructor of this class
["constructor"]() {} // method named "constructor"
static ["constructor"]; // static field named "constructor"
static ["prototype"]; // runtime error, it would be a parsing error without `[]`
}
選項
此規則有一個物件選項
- 將
enforceForClassMembers
設定為false
會停用類別成員的此規則 (預設為true
)。
enforceForClassMembers
預設情況下,此規則也會檢查類別宣告和類別運算式,因為 enforceForClassMembers
的預設值為 true
。
當 enforceForClassMembers
設定為 false
時,此規則將允許在類別欄位、類別方法、類別 getter 和類別 setter 內使用不必要的計算鍵。
使用 { "enforceForClassMembers": false }
選項時,此規則的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": false }]*/
const obj = {
,
,
,
,
};
使用 { "enforceForClassMembers": false }
選項時,此規則的正確程式碼範例
在遊樂場中開啟
/*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": false }]*/
class SomeClass {
["foo"] = "bar";
[42] = "baz";
['a']() {}
get ['b']() {}
set ['c'](value) {}
static ["foo"] = "bar";
static ['baz']() {}
}
何時不使用它
如果您不想收到關於不必要的計算屬性鍵的通知,您可以安全地停用此規則。
版本
此規則是在 ESLint v2.9.0 中引入的。