简体   繁体   中英

tslint: prefer-for-of Expected a 'for-of' loop instead of a 'for' loop

I am getting this tslint error:

prefer-for-of  Expected a 'for-of' loop instead of a 'for' loop with this simple iteration

code:

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;
  }

Can somebody help me to understand and resolve this error? I know there an answer on this question but that's not helping in my situation.

You can use for-of which iterates over the elements of an array to avoid the ts-lint warning:

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

Or you can use a one liner to filter the array:

const selected = options.filter(e=> e.selected).map(e=> e.label);

for-of is much more terse and doesn't require manual iteration. The linter is recommending that you write something like this instead, for the sake of readability:

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

But it would be even better to use reduce in this situation:

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

(You could also use filter followed by map , but that requires iterating over the array twice instead of once)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM