What are iterators in Dojox?

Iterators

The dojox.collections module contains the Iterator class. The Iterator class can be used to iterate over dojox.collections objects and JavaScript arrays.

The Iterator class contains the following methods that can be used to iterate over the collections object.

  1. get: Gets the next element in the collection.

  2. atEnd: Checks if the internal cursor has reached the end of the collection object.

  3. map(function, scope): Executes a function to all the elements in the collection.

  4. reset: Resets the internal cursor to the beginning.

Example

Console
Using Iterator to loop the ArrayList

Explanation

Line 6: We load the Dojo library from the CDN server.

Line 8: We load the dojox/collections/ArrayList module.

Line 9: After the ArrayList class is loaded, we create a new ArrayList object with value [1,2,3,4].

Line 10: We use the getIterator method to get the iterator object for the ArrayList object.

Lines 11–13: We loop the elements of the iterator using the while loop. Here, we check whether the internal cursor of the iterator has reached the end using the atEnd method. If this method returns true , then the loop will end. We also use the get method to move the internal cursor one index forward and get the element at that position.

Line 17: We use the reset method to reset the internal cursor position to the first element of the ArrayList .

Line 21: We use the map method to execute a method to all the elements in the collection. Inside the function, we multiply each element of the ArrayList by 2 and print the value.

Free Resources

Attributions:
  1. undefined by undefined
Copyright ©2024 Educative, Inc. All rights reserved