簡體   English   中英

tslint:prefer-for-of期望'for-of'循環而不是'for'循環

[英]tslint: prefer-for-of Expected a 'for-of' loop instead of a 'for' loop

我收到這個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迭代數組的元素來避免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);

for-of更簡潔,不需要手動迭代。 為了便於閱讀,linter建議你寫這樣的東西:

function collectItems(options) {
  const selected = [];
  for (const each of options) {
    if (each.selected) {
      selected.push(each.label);
    }
  }
  return selected;
}

但在這種情況下使用reduce會更好:

const collectItems = options => options.reduce((selectedLabels, { selected, label }) => {
  if (selected) selectedLabels.push(label)
  return selectedLabels;
}, []);

(您也可以使用filter后跟map ,但這需要迭代數組兩次而不是一次)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM