Index

guard-for-in

要求 for-in 循环包含 if 语句

使用 for in 循环遍历对象时,会包括通过原型链继承的属性。这种行为可能导致你的 for 循环中出现意外的项目。

🌐 Looping over objects with a for in loop will include properties that are inherited through the prototype chain. This behavior can lead to unexpected items in your for loop.

for (key in foo) {
    doSomething(key);
}

对于不支持 ES2022 的代码库,可以使用 Object.prototype.hasOwnProperty.call(foo, key) 来检查该属性是否不是继承的。

🌐 For codebases that do not support ES2022, Object.prototype.hasOwnProperty.call(foo, key) can be used as a check that the property is not inherited.

对于支持 ES2022 的代码库,Object.hasOwn(foo, key) 可以作为一个更简短的替代方案;参见 prefer-object-has-own

🌐 For codebases that do support ES2022, Object.hasOwn(foo, key) can be used as a shorter alternative; see prefer-object-has-own.

请注意,仅检查 foo.hasOwnProperty(key) 在某些情况下可能会导致错误;请参阅 no-prototype-builtins

🌐 Note that simply checking foo.hasOwnProperty(key) is likely to cause an error in some cases; see no-prototype-builtins.

规则详情

🌐 Rule Details

此规则旨在防止因在循环中使用 for in 循环而不对结果进行过滤而可能产生的意外行为。因此,当 for in 循环未使用 if 语句过滤其结果时,它会发出警告。

🌐 This rule is aimed at preventing unexpected behavior that could arise from using a for in loop without filtering the results in the loop. As such, it will warn when for in loops do not filter their results with an if statement.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint guard-for-in: "error"*/

for (key in foo) {
    doSomething(key);
}

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint guard-for-in: "error"*/

for (key in foo) {
    if (Object.hasOwn(foo, key)) {
        doSomething(key);
    }
}

for (key in foo) {
    if (Object.prototype.hasOwnProperty.call(foo, key)) {
        doSomething(key);
    }
}

for (key in foo) {
    if ({}.hasOwnProperty.call(foo, key)) {
        doSomething(key);
    }
}

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

版本

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

进阶读物

资源