no-undef-init

不允许将变量初始化为 undefined

🔧 Fixable

此规则报告的一些问题可通过 --fix 命令行选项自动修复

在 JavaScript 中,已声明但未初始化为任何值的变量会自动获取 undefined 的值。例如:

¥In JavaScript, a variable that is declared and not initialized to any value automatically gets the value of undefined. For example:

var foo;

console.log(foo === undefined);     // true

因此不必将变量初始化为 undefined,例如:

¥It’s therefore unnecessary to initialize a variable to undefined, such as:

var foo = undefined;

避免将变量初始化为 undefined 被认为是最佳实践。

¥It’s considered a best practice to avoid initializing variables to undefined.

规则详情

¥Rule Details

此规则旨在消除初始化为 undefinedvarlet 变量声明。

¥This rule aims to eliminate var and let variable declarations that initialize to undefined.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-undef-init: "error"*/

var foo = undefined;
let bar = undefined;

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-undef-init: "error"*/

var foo;
let bar;

请注意,此规则不检查 const 声明、解构模式、函数参数和类字段。

¥Please note that this rule does not check const declarations, destructuring patterns, function parameters, and class fields.

此规则的附加正确代码示例:

¥Examples of additional correct code for this rule:

在线运行
/*eslint no-undef-init: "error"*/

const foo = undefined;

let { bar = undefined } = baz;

[quux = undefined] = quuux;

(foo = undefined) => {};

class Foo {
    bar = undefined;
}

何时不使用

¥When Not To Use It

在一种情况下,初始化 undefined 的行为与忽略初始化的行为不同,那就是 var 声明发生在循环内。例如:

¥There is one situation where initializing to undefined behaves differently than omitting the initialization, and that’s when a var declaration occurs inside of a loop. For example:

此规则的错误代码示例:

¥Example of incorrect code for this rule:

在线运行
/*eslint no-undef-init: "error"*/

for (i = 0; i < 10; i++) {
    var x = undefined;
    console.log(x);
    x = i;
}

在这种情况下,var x 被吊出循环,有效地创建:

¥In this case, the var x is hoisted out of the loop, effectively creating:

var x;

for (i = 0; i < 10; i++) {
    x = undefined;
    console.log(x);
    x = i;
}

如果要删除初始化,则循环的行为会发生变化:

¥If you were to remove the initialization, then the behavior of the loop changes:

for (i = 0; i < 10; i++) {
    var x;
    console.log(x);
    x = i;
}

这段代码相当于:

¥This code is equivalent to:

var x;

for (i = 0; i < 10; i++) {
    console.log(x);
    x = i;
}

这会产生与在循环中定义 var x = undefined 不同的结果,因为 x 不再每次通过循环都重置为 undefined

¥This produces a different outcome than defining var x = undefined in the loop, as x is no longer reset to undefined each time through the loop.

如果你在循环内使用这样的初始化,那么你应该禁用此规则。

¥If you’re using such an initialization inside of a loop, then you should disable this rule.

此规则的正确代码示例,因为它在特定行上被禁用:

¥Example of correct code for this rule, because it is disabled on a specific line:

在线运行
/*eslint no-undef-init: "error"*/

for (i = 0; i < 10; i++) {
    var x = undefined; // eslint-disable-line no-undef-init
    console.log(x);
    x = i;
}

版本

此规则是在 ESLint v0.0.6 中引入。

资源

ESLint 中文网
粤ICP备13048890号