React - for文でUsing ‘ForInStatement’ is not allowedと怒られる

Reactで配列やオブジェクトをfor文で回そうとするとESLintにUsing 'ForInStatement' is not allowed.eslint(no-restricted-syntax)と怒られてしまします。


NG例: 配列をfor...inで回す

const arr = [1, 2, 3, 4];

for (e in arr) {
    console.log(e);
}
// Using 'ForInStatement' is not allowed.eslint(no-restricted-syntax)


NG例: オブジェクトをfor..ofで回す

const obj = {
    name: 'tom',
    age: 24,
    height: 180,
};

for (e of obj) {
    console.log(e)
}
// Using 'ForOfStatement' is not allowed.eslint(no-restricted-syntax)


対処法

配列の場合

配列の場合はarray.forEach()で回してあげます。

const arr = [1, 2, 3, 4];

arr.forEach(e => console.log(e));
// 1
// 2
// 3
// 4


オブジェクトの場合

Object.keys().forEach()を使います。Object.forEach()ではないので注意。

const obj = {
    name: 'tom',
    age: 24,
    height: 180,
};

Object.keys(obj).forEach((key, index) => {
    console.log(obj[key]);
});
// tom
// 24
// 180