## javascript设计模式之迭代器模式

2020年02月18日 ⁄ 共 2174字 ⁄ 字号 评论关闭

//实现一个jq的\$.each()迭代器var arr = [1, 2, 3, 4, 5, 6, 7, 8]var each = function(arr, callback){ for(var i=0; i<arr.length; i++){ callback.call(null, i, arr[i]) //把下标和元素当作参数传递给callback参数 }}each(arr, function(i, n){ console.log(i, n);})//类似于jquery的 \$.each(arr, function(i,n){})

//对两个数组做相等性判断时，如果不改迭代器内部方法实现，只能通过each的回调函数进行实现，虽然能实现，但不是很优雅。let compare = function (ary1, ary2) { if(ary1.length !== ary2.length){ throw new Error('ar1和ary2长度不相等。') } each(ary1, function (i, n) { if(n !== ary2[i] ){ throw new Error('ary1和ary2不相等。') } }) console.log('ary1和ary2相等!');}compare([1,2,3], [1,2, 3])

let Iterator = function (obj) { let current = 0; let next = function () { current += 1 } let isNotDone = function () { return current <= obj.length } let getCurrentItem = function () { return obj[current]; } return { next, isNotDone, getCurrentItem }}//外部迭代器通过next方法进行手工迭代let arr = ['a', true, false, '10', 88, 741]let iterator1 = Iterator(arr)console.log(iterator1.getCurrentItem()); // aiterator1.next()console.log(iterator1.getCurrentItem()); // trueiterator1.next()console.log(iterator1.getCurrentItem()); // falseiterator1.next()console.log(iterator1.getCurrentItem()); // '10'//改写compare函数let compare = function (iterator1, iterator2) { while(iterator1.isNotDone() && iterator2.isNotDone()){ if(iterator1.getCurrentItem() !== iterator2.getCurrentItem()){ throw new Error('iterator1和iterator2不相等。') } iterator1.next() iterator2.next() } console.log('iterator1和iterator2相等。');}let iterator1 = Iterator([1, 2, 3, 4])let iterator2 = Iterator([1, 2, 3, 4, 5])compare(iterator1, iterator2) //iterator1和iterator2不相等。

let Iterator = function (array) { let nextIndex = 0; return { next: function () { return nextIndex < array.length ? {value: array[nextIndex++], done: false}: {done: true}; } }}let it = Iterator(['a', 3, 10])console.log(it.next().value); //aconsole.log(it.next().value); //3console.log(it.next().value); //10 迭代到这步已经把所有值都迭代完成console.log(it.next().done); //true