Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript tslint:对于预期的a';对于';循环而不是';对于';环_Javascript_Typescript_For Loop_Tslint - Fatal编程技术网

Javascript tslint:对于预期的a';对于';循环而不是';对于';环

Javascript tslint:对于预期的a';对于';循环而不是';对于';环,javascript,typescript,for-loop,tslint,Javascript,Typescript,For Loop,Tslint,我得到这个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];

我得到这个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(设i=0;i
有人能帮我理解并解决这个错误吗?
我知道在这个问题上存在分歧,但这对我的处境没有帮助

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;
}, []);

(您也可以使用
过滤器
后跟
映射
,但这需要在数组上迭代两次而不是一次)

您可以使用
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);

为什么另一个问题没有帮助?