How to iterate over a Set in TypeScript?

后端 未结 5 1889
逝去的感伤
逝去的感伤 2021-01-03 19:36

How do you iterate over a set in TypeScript? for..of does not work:

\'Set\' is not an array type or a string type

.for

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 20:18

    You can still use .forEach with the correct this by using a regular function instead of an arrow function

    mySet.forEach(function(item){
        expect(this).toEqual(item);
    });
    

    Compared to

    class MyClass{
        ...
        doSomething():{
            mySet.forEach((item) => {
                expect(this instanceof MyClass).toEqual(true);
            });
        }
    }
    

    Another way to iterate is to use a for loop over the values

    for(item of mySet.values()){
        ...
    }
    

    More information on iterating Set with foreach can be found here

提交回复
热议问题