no-undefined
禁止使用 undefined 作为标识符
此规则目前已 冻结,不接受功能请求。
JavaScript 中的 undefined 变量实际上是全局对象的一个属性。因此,在 ECMAScript 3 中,可以覆盖 undefined 的值。虽然 ECMAScript 5 不允许覆盖 undefined,但仍然可以覆盖 undefined,例如:
¥The undefined variable in JavaScript is actually a property of the global object. As such, in ECMAScript 3 it was possible to overwrite the value of undefined. While ECMAScript 5 disallows overwriting undefined, it’s still possible to shadow undefined, such as:
function doSomething(data) {
const undefined = "hi";
// doesn't do what you think it does
if (data === undefined) {
// ...
}
}
因为 undefined 可以被覆盖或隐藏,读取 undefined 可能会给出一个意想不到的值。(null 的情况并非如此,它是一个始终产生相同值的关键字。)为了防止这种情况,你可以避免使用 undefined,这是一些样式指南建议的内容,也是此规则强制执行的内容。这些风格指南还建议:
¥Because undefined can be overwritten or shadowed, reading undefined can give an unexpected value. (This is not the case for null, which is a keyword that always produces the same value.) To guard against this, you can avoid all uses of undefined, which is what some style guides recommend and what this rule enforces. Those style guides then also recommend:
-
应该是
undefined的变量只是未初始化。(所有未初始化的变量在 JavaScript 中自动获取undefined的值。)¥Variables that should be
undefinedare simply left uninitialized. (All uninitialized variables automatically get the value ofundefinedin JavaScript.) -
检查值是否为
undefined应使用typeof完成。¥Checking if a value is
undefinedshould be done withtypeof. -
如有必要,使用
void运算符生成undefined的值。¥Using the
voidoperator to generate the value ofundefinedif necessary.
作为替代方案,你可以使用 no-global-assign 和 no-shadow-restricted-names 规则来防止 undefined 被遮蔽或分配不同的值。这确保了 undefined 将始终保持其原始预期值。
¥As an alternative, you can use the no-global-assign and no-shadow-restricted-names rules to prevent undefined from being shadowed or assigned a different value. This ensures that undefined will always hold its original, expected value.
规则详情
¥Rule Details
此规则旨在消除对 undefined 的使用,因此,每当使用它时都会生成警告。
¥This rule aims to eliminate the use of undefined, and as such, generates a warning whenever it is used.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-undefined: "error"*/
const foo = undefined;
const undefined = "foo";
if (foo === undefined) {
// ...
}
function baz(undefined) {
// ...
}
bar(undefined, "lorem");
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-undefined: "error"*/
const foo = void 0;
const Undefined = "foo";
if (typeof foo === "undefined") {
// ...
}
global.undefined = "foo";
bar(void 0, "lorem");
何时不使用
¥When Not To Use It
如果你想允许在你的代码中使用 undefined,那么你可以安全地关闭此规则。
¥If you want to allow the use of undefined in your code, then you can safely turn this rule off.
相关规则
版本
此规则是在 ESLint v0.7.1 中引入。