sindresorhus/eslint-plugin-unicorn

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

Chiusa

#1452 aperta il 27 lug 2021

 (5 commenti) (1 reazione) (0 assegnatari)JavaScript (468 fork)user submission
bughelp wantedtypes

Metriche repository

Star
 (5022 stelle)
Metriche merge PR
 (Merge medio 4h 30m) (26 PR mergiate in 30 g)

Descrizione

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']
}

Guida contributor