首页 > 解决方案 > 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;
  }

有人可以帮我理解和解决这个错误吗?我知道这个问题有答案,但这对我的情况没有帮助。

标签: javascripttypescriptfor-looptslint

解决方案


您可以使用for-ofwhich 迭代数组的元素以避免 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);

推荐阅读