Iterator pattern
1. Definition of iterator pattern
An Iterator pattern provides a way to access elements of an aggregate object sequentially without exposing the internal representation of the object.
2. Classification of iterators
- Inner iterator
function each(arr, callback) { for (let i = 0; i < arr.length; I++) {callback (I, arr [I])}} each ([3, 4, 5, 6], the function (index, val) {the console. The log (` ${index} element has a value of ${val} `)})Copy the code
The first argument represents the current array to iterate over, and the second argument represents the callback function for the current iteration
- External iterator
var Iterator = function (arr) { var current = 0; var next = function () { current += 1; } var isDone = function () { return current > arr.length; } var getCurrentItem = function () { return arr[current]; } return { next: next, isDone: isDone, getCurrentItem: getCurrentItem, length: arr.length } } var iteratorDemo = Iterator([1, 2, 3, 4, 5]) while (! iteratorDemo.isDone()) { console.log(iteratorDemo.getCurrentItem()) iteratorDemo.next() }Copy the code
Iterator returns an object with the interface next to perform the next iteration; IsDone, whether the iteration is over; GetCurrentItem, item of the current iteration; Length, the length of the current iterator.
Additional: use of the map method
var arr = [1, 2, 3, 4, 5]
var newArr = arr.map((val, index, arr) => {
return val*2
})
console.log(newArr)
Copy the code
Arr can call the map method, which takes a callback function that takes the current value val, the current index index and the current array ARr. Furthermore, a call to the entire method can return the new array evaluated by each val.
Additional: implementation of the map method
In the process of an interview in a company was asked to handwritten map implementation, the idea is as follows
Var arr = [1, 2, 3, 4, 5] array.prototype mapTest = function (callback) {let arr = this; let newArr = [] for (let i = 0; i < arr.length; I ++) {newArr[I] = callback(arr[I], I, arr)} Var newArr = arr.maptest ((val, index, arr) => {return val*2}) console.log(newArr)Copy the code
Summary: JavaScript already has multiple iterators built in, such as forEach, Map, Filter, and Reduce.
Reference Book: JavaScript Design Patterns and Development Practices (Tseng)