prefer-const
注意: 此规则是
recommended
规则集的一部分。在
deno.json
中启用完整规则集{ "lint": { "tags": ["recommended"] } }
使用 Deno CLI 启用完整规则集
deno lint --tags=recommended
自 ES2015 以来,JavaScript 支持使用 let
和 const
来声明变量。如果变量使用 let
声明,则它们变为可变的;之后我们可以为它们设置其他值。同时,如果使用 const
声明,则它们是不可变的;我们不能对它们执行重新赋值。
一般来说,为了使代码库更健壮、更易于维护和更易读,强烈建议尽可能使用 const
而不是 let
。可变变量越少,在阅读代码时就越容易跟踪变量状态,从而减少编写错误代码的可能性。因此,此 lint 规则检查是否存在可以潜在地使用 const
而不是 let
声明的变量。
请注意,此规则不检查 var
变量。相反,no-var
规则 负责检测和警告 var
变量。
无效
let a = 0;
let b = 0;
someOperation(b);
// `const` could be used instead
for (let c in someObject) {}
// `const` could be used instead
for (let d of someArray) {}
// variable that is uninitialized at first and then assigned in the same scope is NOT allowed
// because we could simply write it like `const e = 2;` instead
let e;
e = 2;
有效
// uninitialized variable is allowed
let a;
let b = 0;
b += 1;
let c = 0;
c = 1;
// variable that is uninitialized at first and then assigned in the same scope _two or more times_ is allowed
// because we cannot represent it with `const`
let d;
d = 2;
d = 3;
const e = 0;
// `f` is mutated through `f++`
for (let f = 0; f < someArray.length; f++) {}
// variable that is initialized (or assigned) in another scope is allowed
let g;
function func1() {
g = 42;
}
// conditionally initialized variable is allowed
let h;
if (trueOrFalse) {
h = 0;
}