gpt4 book ai didi

javascript - tslint:prefer-for-of 预期为 'for-of' 循环而不是 'for' 循环

转载 作者:搜寻专家 更新时间:2023-10-30 21:04:26 27 4
gpt4 key购买 nike

我收到这个 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关于这个问题,但这对我的情况没有帮助。

最佳答案

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

关于javascript - tslint:prefer-for-of 预期为 'for-of' 循环而不是 'for' 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50810455/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com