最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript loop through a Set of values - Stack Overflow

programmeradmin2浏览0评论

I have the following weird issue on my code using 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. '

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

I have the following weird issue on my code using 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. '

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

Share Improve this question asked Feb 20, 2018 at 13:32 Bad_PanBad_Pan 50814 silver badges24 bronze badges 2
  • 1 possible duplicate of stackoverflow./questions/35193471/… – Safiyya Commented Feb 20, 2018 at 13:35
  • 2 Possible duplicate of How to iterate over a Set in TypeScript? – Ele Commented Feb 20, 2018 at 13:43
Add a ment  | 

3 Answers 3

Reset to default 4

Set are not define in TS, you need to configure TS with es2017.object or convert Set values to array :

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

You can use fruitSet.forEach( fruit => ... )

If you want to use for..of, try spread operator: 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.

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

instead of

for (const _ of range(0, 7)) {
    // Some code
}
发布评论

评论列表(0)

  1. 暂无评论