[英]tslint: prefer-for-of Expected a 'for-of' loop instead of a 'for' loop
I am getting this tslint error: 我收到这个tslint错误:
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: 您可以使用for-of
迭代数组的元素来避免ts-lint警告:
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. for-of
更简洁,不需要手动迭代。 The linter is recommending that you write something like this instead, for the sake of readability: 为了便于阅读,linter建议你写这样的东西:
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: 但在这种情况下使用reduce
会更好:
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) (您也可以使用filter
后跟map
,但这需要迭代数组两次而不是一次)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.