首页 > 解决方案 > eslint 使用 for 循环或 forEach

问题描述

有 eslint 规则unicorn/no-array-for-each链接)。

Use `for…of` instead of `Array#forEach(…)`            unicorn/no-array-for-each

独角兽规则的动机是它支持早期返回并且声称更快。对于像itemList = [{a:1},{a:2},{a:3}].

for (const item of itemList) {
    if (item.a > 1) break;
    console.log(item.a)
}

但是,它会进入 eslint 错误no-restricted-syntax链接)。

iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations  no-restricted-syntax

它说 for 循环是重量级的。这两个规则似乎相互冲突,启用哪一个更有意义?

标签: javascripteslint

解决方案


正如@VLAX 所说,传统for循环满足这两个规则。

for (let index = 0, l = itemList.length; index < l; index += 1) {
    const item = itemList[index];
    if (item.a > 1) break;
    console.log(item.a)  
}

推荐阅读