Loop through a Set using Javascript

Web DevelopmentFront End TechnologyJavascript

In the set that we implemented, we can create a for each function in our class and accept a callback that we can call on every element. Let's see how we can implement such a function − 

Example

forEach(callback) {
   for (let prop in this.container) {
      callback(prop);
   }
}

You can test this using − 

Example

const testSet = new MySet();

testSet.add(1);
testSet.add(2);
testSet.add(5);

testSet.forEach(elem => console.log(`Element is ${elem}`));

Output

This will give the output −

Element is 1
Element is 2
Element is 5

The ES6 Set API also provides the same functionality using the forEach method.

raja
Published on 27-Jun-2018 15:58:06
Advertisements