迭代器是指通過一種形式依次遍曆數組,對象,或者類數組結構中的每個元素. 常見的有jquery中的each方法, ES5自帶的forEach方法. 下麵我們就來自定義一個類似jquery或者ES5的迭代器方法 輸出結果: ["zhangsan", "lisi", "ghostwu"] "zhangsa ...
迭代器是指通過一種形式依次遍曆數組,對象,或者類數組結構中的每個元素. 常見的有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 : current 16 }; 17 } 18 var obj = null; 19 obj = Iterator( [ 10, 20, 30 ] ); 20 console.log( obj.current(), obj.isDone() ); // 10, false 21 obj.next(); 22 console.log( obj.current(), obj.isDone() ); // 20, false 23 obj.next(); 24 console.log( obj.current(), obj.isDone() ); // 30, false 25 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 : current 16 }; 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 ) );