The core of the iterator pattern is to provide a way for you to traverse every element in the object and do similar processing to them.
It's what people say-a common array processing method. Such as forEach, map, some, every and so on, usually we use to deal with array methods to give them a tall name is iterator.
In JavaScript, in addition to arrays, ordinary objects can also be traversed by for in, so we can write a general iterator to deal with "objects".
function iterator(obj,fn){
if (Object.prototype.toString.call(obj) === "[object Array]") {
for(let i=0;i<obj.length;i++){
fn.call(null,obj[i],i)
}
}else if(Object.prototype.toString.call(obj)==='[object Object]'){
for(let i in obj){
fn.call(null,obj[i],i)
}
}else{
throw new Error('请传入一个数组或对象')
}
}
iterator([3,6,9],function(val,index){
console.log(val,index)
})
iterator({
'a':'aaa',
'b':'bbb'
},function(val,key){
console.log(val,key)
})