迭代器是指通过一种形式依次遍历数组,对象,或者类数组结构中的每个元素. 常见的有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
二、利用迭代器,判断两个数组的长度和对应的位置的值是否相等
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 function isEqual( arr1, arr2 ){ 7 var flag = false; 8 if( arr1.length != arr2.length ){ 9 throw new Error( '数组的长度不相等' );10 }11 each( arr1, function( val, key ){12 if ( val != arr2[key] ) {13 throw new Error('数组的第' + (key+1) + '项不相等');14 }15 });16 return true;17 }18 console.log( isEqual( [ 10, 20, 30 ], [ 10, 20, 30 ] ) );
三、另一种迭代器
1 function Iterator( obj ){ 2 var curInd = 0; 3 var next = function(){ 4 curInd += 1; 5 }; 6 var isDone = function(){ 7 return curInd >= obj.length; 8 }; 9 var current = function(){10 return obj[curInd];11 };12 return {13 next : next,14 isDone : isDone,15 current : current16 };17 }18 var obj = null;19 obj = Iterator( [ 10, 20, 30 ] );20 console.log( obj.current(), obj.isDone() ); // 10, false21 obj.next();22 console.log( obj.current(), obj.isDone() ); // 20, false23 obj.next();24 console.log( obj.current(), obj.isDone() ); // 30, false25 obj.next();26 console.log( obj.current(), obj.isDone() ); // undefined, true
四,使用上面的迭代器,改写两个数组的比较
1 function Iterator( obj ){ 2 var curInd = 0; 3 var next = function(){ 4 curInd += 1; 5 }; 6 var isDone = function(){ 7 return curInd >= obj.length; 8 }; 9 var current = function(){10 return obj[curInd];11 };12 return {13 next : next,14 isDone : isDone,15 current : current16 };17 }18 19 function compare( it1, it2 ){20 while( !it1.isDone() && !it2.isDone() ){21 if( it1.current() != it2.current() ){22 throw new Error( '数组不相等' );23 }24 it1.next();25 it2.next();26 }27 return true;28 }29 30 var Iterator1 = Iterator([ 10, 20, 30 ]);31 var Iterator2 = Iterator([ 10, 20, 30 ]);32 33 console.log( compare( Iterator1, Iterator2 ) );