Typescript 循环遍历一组值

Typescript loop through a Set of values

我在使用 Typescript 2.6 的代码中遇到以下奇怪问题。我试图遍历一组字符串值,但出现以下错误,我不明白为什么。

'Type 'Set' is not an array type or a string type. '

这是我的资料:

loopThroughSet(): void {

        let fruitSet = new Set()
        .add('APPLE')
        .add('ORANGE')
        .add('MANGO');

        for (let fruit of fruitSet) {
            console.log(fruit);
        }
}

有谁知道问题出在哪里? 提前致谢

Set 未在 TS 中定义,您需要使用 es2017.object 配置 TS 或将 Set 值转换为数组:

for (var item of Array.from(fruitSet.values())) {
  console.log(item);
}

您可以使用fruitSet.forEach( fruit => ... )

如果你想使用for..of,尝试展开运算符:for (const fruit of [...fruitsSet]) { ... }

在我的例子中,我需要在没有 定义 使用 标记为的变量的情况下遍历七个项目的范围unused by ESLint, and the spread syntax帮了大忙。

[...Array(7)].map(() => {
    // some code
});

而不是

for (const _ of range(0, 7)) {
    // Some code
}