【问题标题】:tslint: prefer-for-of Expected a 'for-of' loop instead of a 'for' looptslint: prefer-for-of 期望一个“for-of”循环而不是一个“for”循环
【发布时间】:2018-11-21 10:55:28
【问题描述】:
我收到这个 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;
}
谁能帮我理解和解决这个错误?
我知道在这个问题上有一个answer,但这对我的情况没有帮助。
【问题讨论】:
标签:
javascript
typescript
for-loop
tslint
【解决方案1】:
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,但这需要迭代数组两次而不是一次)
【解决方案2】:
您可以使用 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);