[js高手之路] 设计模式系列课程 - 迭代器(1)

时间:2021-07-29 19:08:32

迭代器是指通过一种形式依次遍历数组,对象,或者类数组结构中的每个元素. 常见的有jquery中的each方法, ES5自带的forEach方法. 下面我们就来自定义一个类似jquery或者ES5的迭代器方法

1         function each( arr, fn ) {
2 for( var i = 0, len = arr.length; i < len; i++ ){
3 fn.call( arr, arr[i], i );
4 }
5 }
6 each( [ 'zhangsan', 'lisi', 'ghostwu' ], function( val, key ){
7 console.log( this, val, key );
8 });

输出结果:

["zhangsan", "lisi", "ghostwu"] "zhangsan" 0
["zhangsan", "lisi", "ghostwu"] "lisi" 1
["zhangsan", "lisi", "ghostwu"] "ghostwu" 2

二、利用迭代器,判断两个数组的长度和对应的位置的值是否相等

         function each( arr, fn ) {
for( var i = 0, len = arr.length; i < len; i++ ){
fn.call( arr, arr[i], i );
}
}
function isEqual( arr1, arr2 ){
var flag = false;
if( arr1.length != arr2.length ){
throw new Error( '数组的长度不相等' );
}
each( arr1, function( val, key ){
if ( val != arr2[key] ) {
throw new Error('数组的第' + (key+1) + '项不相等');
}
});
return true;
}
console.log( isEqual( [ 10, 20, 30 ], [ 10, 20, 30 ] ) );

三、另一种迭代器

         function Iterator( obj ){
var curInd = 0;
var next = function(){
curInd += 1;
};
var isDone = function(){
return curInd >= obj.length;
};
var current = function(){
return obj[curInd];
};
return {
next : next,
isDone : isDone,
current : current
};
}
var obj = null;
obj = Iterator( [ 10, 20, 30 ] );
console.log( obj.current(), obj.isDone() ); // 10, false
obj.next();
console.log( obj.current(), obj.isDone() ); // 20, false
obj.next();
console.log( obj.current(), obj.isDone() ); // 30, false
obj.next();
console.log( obj.current(), obj.isDone() ); // undefined, true

四,使用上面的迭代器,改写两个数组的比较

         function Iterator( obj ){
var curInd = 0;
var next = function(){
curInd += 1;
};
var isDone = function(){
return curInd >= obj.length;
};
var current = function(){
return obj[curInd];
};
return {
next : next,
isDone : isDone,
current : current
};
} function compare( it1, it2 ){
while( !it1.isDone() && !it2.isDone() ){
if( it1.current() != it2.current() ){
throw new Error( '数组不相等' );
}
it1.next();
it2.next();
}
return true;
} var Iterator1 = Iterator([ 10, 20, 30 ]);
var Iterator2 = Iterator([ 10, 20, 30 ]); console.log( compare( Iterator1, Iterator2 ) );