javascript - tslint: prefer-for-of 期望一个“for-of”循环而不是一个“for”循环
问题描述
我收到这个 tslint 错误:
prefer-for-of Expected a 'for-of' loop instead of a 'for' loop with this simple iteration
代码:
function collectItems(options) {
const selected = [];
for (let i = 0; i < options.length; i++) {
const each = options[i];
if (each.selected) {
selected.push(each.label);
}
}
return selected;
}
有人可以帮我理解和解决这个错误吗?我知道这个问题有答案,但这对我的情况没有帮助。
解决方案
您可以使用for-of
which 迭代数组的元素以避免 ts-lint 警告:
function collectItems(options) {
const selected = [];
for (const each of options) {
if (each.selected) {
selected.push(each.label);
}
}
return selected;
}
或者您可以使用一个衬里来过滤数组:
const selected = options.filter(e=> e.selected).map(e=> e.label);
推荐阅读
- flutter - 如何将我的 VIsual Studio Code 构建的应用程序发布为 APK?
- flutter - 如何在滑块 FLUTTER 中执行操作
- java - 冒泡排序 String 数组和 int 数组
- sql - 在 DataStudio 的 SQL 查询中使用 timestamp_trunc 中的参数
- node.js - 将 setTimeout 用于 Discord 机器人响应延迟和自定义“正在输入”
- node.js - 设置 Redis cookie 时,Apollo 客户端未连接到服务器
- python - 将 Class 方法应用于 Class 列表中的所有 Class 方法
- xml - 为什么必须在 XML 属性中转义 <?
- javascript - Condition 用初始值检查 Redux state
- php - Laravel 7:订单数据无法进入数据库并报错