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);
    }
}

版本

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

进阶读物

资源

ESLint 中文网
粤ICP备13048890号