[英]Typescript loop through a Set of values
I have the following weird issue on my code using Typescript 2.6.我使用 Typescript 2.6 的代码有以下奇怪的问题。 I 'm trying to loop through a Set of string values but I get the following error and I don't understand why.
我正在尝试遍历一组字符串值,但出现以下错误,我不明白为什么。
'Type 'Set' is not an array type or a string type.
'Type 'Set' 不是数组类型或字符串类型。 '
'
Here is what I have:这是我所拥有的:
loopThroughSet(): void {
let fruitSet = new Set()
.add('APPLE')
.add('ORANGE')
.add('MANGO');
for (let fruit of fruitSet) {
console.log(fruit);
}
}
Does anyone knows what's the problem?有谁知道是什么问题? Thanks in advance
提前致谢
Set are not define in TS, you need to configure TS with es2017.object or convert Set values to array : Set 没有在 TS 中定义,你需要使用 es2017.object 配置 TS 或者将 Set 值转换为数组:
for (var item of Array.from(fruitSet.values())) {
console.log(item);
}
You can use fruitSet.forEach( fruit => ... )
你可以使用
fruitSet.forEach( fruit => ... )
If you want to use for..of
, try spread operator: for (const fruit of [...fruitsSet]) { ... }
如果您想使用
for..of
,请尝试传播运算符: for (const fruit of [...fruitsSet]) { ... }
In my case, I needed to iterate through a range of seven items without defining and using a variable that would be marked as unused by ESLint , and the spread syntax helped a lot.在我的例子中,我需要在不定义和使用被 ESLint标记为未使用的变量的情况下遍历一系列的七个项目,并且传播语法有很大帮助。
[...Array(7)].map(() => {
// some code
});
instead of而不是
for (const _ of range(0, 7)) {
// Some code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.