javascript - 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 循环是重量级的。这两个规则似乎相互冲突,启用哪一个更有意义?
解决方案
正如@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)
}
推荐阅读
- reactjs - 删除后如何清理“react-beautiful-dnd”可拖动?
- python - 错误处理:如何正确确定异常的优先级
- c++ - 为什么这段代码适用于 8 个不同的测试用例,除了 C++ 中的 1 个?
- mysql - 如何在 WHERE 命令中使用包含空格的 SQL 元素?
- laravel - Laravel 6没有这样的文件或目录驱动程序PDOConnection
- android - Android 单元测试:如何模拟包含 MutableLiveData 但仅公开 LiveData 的对象?
- java - 在 Spring Boot 中膨胀实体中的内部类
- javascript - Vuex `people[0] = { age: people[0].age + 1 };` 不会触发重新渲染,为什么?
- angular - Angular 9 在另一个方法中的 promise 的响应值是未定义的,但是从 promise 方法可以清楚地得到安慰
- mysql - MySQL - 在 SELECT 期间匹配和替换来自另一个表的列中的文本