![](/img/trans.png)
[英][tslint]Expected a 'for-of' loop instead of a 'for' loop with this simple iteration (prefer-for-of)
[英]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.