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的值。) - 检查一个值是否为
undefined应该使用typeof。 - 在必要时使用
void运算符生成undefined的值。
作为替代,你可以使用 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");
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
何时不使用
🌐 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 中引入。