sindresorhus/eslint-plugin-unicorn

`no-array-for-each` bad autofix with `Map`

クローズ

#1,452 opened on 2021/07/27

 (5 件のコメント) (1 件のリアクション) (0 人の担当者)JavaScript (468 件のフォーク)user submission
bughelp wantedtypes

Repository metrics

Stars
 (5,022 個のスター)
PR merge metrics
 (平均マージ 4h 30m) (30d で 26 merged PRs)

説明

When the no-array-for-each rule is enabled (as recommended) it reports errors when forEach is used with other types that aren’t arrays, like Map or Set. (Or any custom object with a forEach method potentially.)

const map = new Map();
map.forEach((i) => console.log(i));
//  ^^^^^^^
//  Error: Do not use `Array#forEach(…)`

const set = new Set();
set.forEach((i) => console.log(i));
//  ^^^^^^^
//  Error: Do not use `Array#forEach(…)`

This is most important for Map, where forEach passes the mapped value as the first argument to its callback, but the current auto-fix (for...of) will pass [key, value]:

const map = new Map([['key', 'value']]);

// Before auto-fix
map.forEach((value) => console.log(value)); // 'value'

// After auto-fix
for (const value of map) {
  console.log(value); // ['key', 'value']
}

コントリビューターガイド