Javascript tslint:对于预期的a';对于';循环而不是';对于';环
我得到这个tslint错误: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];
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);
为什么另一个问题没有帮助?