Skip to content

useGuardForIn

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"suspicious": {
"useGuardForIn": "error"
}
}
}
}

¥Description

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

¥Require for-in loops to include an if statement.

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

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

对于不支持 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) 作为更简洁、更可靠的替代方案。

¥For codebases that do support ES2022, Object.hasOwn(foo, key) can be used as a shorter and more reliable alternative.

¥Examples

¥Invalid

for (key in foo) {
doSomething(key);
}
code-block.js:1:1 lint/suspicious/useGuardForIn ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The body of a for-in should be wrapped in an `if` statement.

> 1 │ for (key in foo) {
^^^^^^^^^^^^^^^^^^
> 2 │ doSomething(key);
> 3 │ }
^
4 │

Looping over the object with for-in loop will include properties that are inherited through the prototype chain, the behaviour can lead to some unexpected items in your loop.

To resolve this issue, add an if statement like `if (Object.hasOwn(foo, key)) {…}` to filter out the extraneous properties.

¥Valid

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

¥Related links