In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use iterator pattern". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use iterator pattern".
You will learn
The meaning of iterator pattern
Implement an array iterator
Implement an object iterator
Implement path lookup / assignment iterator
How to use the idea of iterator to solve the problem of branch loop nesting
Implement a picture player
Text
1. The meaning of iterator
The main idea of the iterator pattern is that the internal elements of the object can be accessed in a certain order without exposing the internal structure of the object.
In fact, many methods in javascript use the idea of iterator, such as array forEach,every,find,some,map,entries, etc., these operations greatly simplify our logic operation, and then let's take a look at its specific application.
two。 Implement an array iterator
We all know the forEach method of arrays in javascript, so can we implement one ourselves without this method?
/ / array iterator let eachArr = function (arr, fn) {let I = 0, len = arr.length; for (; I
< len; i++) { if(fn.call(arr[i], i, arr[i]) === false) { break; } } } // 使用 eachArr([1,2,3,4], (index, value) =>{console.log (index, value)})
3. Implement an object iterator
An object iterator is similar to an array iterator, except that you pass parameters as follows:
/ object iterator let eachObj = function (obj, fn) {for (let key in obj) {if (fn.call (obj [key], key, obj [key]) = false) {break;} / / use eachObj ({a: 11, b: 12}, (key, value) = > {console.log (key, value)})
4. Implement path lookup / assignment iterator
Sometimes when we manipulate certain attributes of an object, we don't know whether the server will correctly return the attribute or the parent attribute of the attribute to us. At this time, our direct access through point syntax or [] syntax will lead to code errors, so we need to do security checking at each layer, which will result in a lot of bloated code, such as:
Let obj = {}; / / get obj.num.titNum let titNum = obj.num.titNum; / / error let titNum = obj & & obj.num & & obj.num.titNum; / / correct
Through iterators, we can greatly reduce this check and achieve more robust code patterns:
Let findObjAttr = function (obj, key) {if (! obj | |! key) {return undefined} let result = obj; key = key.split ('.'); for (let I = 0; len = key.length; I)
< len; i++) { if(result[key[i]] !== undefined) { result = result[key[i]] }else { return undefined } } return result } // 使用 let a = { b: { c: { d: 1 } } }; findObjAttr(a, 'a.b.c.d') // 1 这种方式是不是有点类似于lodash的对象/数组查找器呢?同理,我们也可以实现路径赋值器,如下所示: let setObjAttr = function(obj, key, value){ if(!obj) { return false } let result = obj, key = key.split('.'); for(let i =0, len = key.length; i< len - 1; i++){ if(result[key[i]] === undefined) { result[key[i]] = {}; } if(!(result[key[i]] instanceof Object)){ // 如果第i层对应的不是一个对象,则剖出错误 throw new Error('is not Object') return false } result = result[key[i]] } return result[key[i]] = val } // 使用 setObjAttr(obj, 'a.b.c.d', 'xuxi') 5.如何用迭代器的思想解决分支循环嵌套问题 分支循环嵌套的问题主要是指在循环体中还需要进行额外的判断,如果判断条件变多,将会造成严重的性能开销问题,如下面的例子: // 数据分组 function group(name, num) { let data = []; for(let i = 0; i < num; i++){ switch(name) { case 'header': data[i][0] = 0; data[i][1] = 1; break; case 'content': data[i][0] = 2; data[i][1] = 3; break; case 'footer': data[i][0] = 4; data[i][1] = 532; break; default: break; } } return data } 由以上分析可知,上面的代码还有很多优化空间,因为每一次遍历都要进行一次分支判断,那么如果num变成100000,且name的种类有100种,那么我们就要做100000*100种无用的分支判断,这样无疑会让你的代码在大数据下卡死。不过我们可以通过以下这种方式优化它: // 数据分组 function group(name, num) { let data = []; let strategy = function() { let deal = { 'default': function(i){ return }, 'header': function(i){ data[i][0] = 0; data[i][1] = 1; }, 'content': function(i){ data[i][0] = 2; data[i][1] = 3; }, //... } return function(name) { return deal[name] || deal['default'] } }(); // 迭代器处理数据 function _each(fn) { for(let i = 0; i < num; i++){ fn(i) } } _each(strategy(name)) return data } 这样我们就能避免分支判断,极大的提高了代码效率和性能。 6.实现一个图片播放器 图片播放器主要有以上几个功能,上一页,下一页,首页,尾页,自动播放按钮,停止按钮。具体组件的设计机构可以参考我写的demo: // 图片播放器 let imgPlayer = function(imgData, box) { let container = box && document.querySelector(box) || document, img = container.querySelector('img'), // 获取图片长度 len = imgData.length, // 当前索引值 index = 0; // 初始化图片 img.src = imgData[0]; var timer = null; return { // 获取第一个图片 first: function() { index = 0 img.src = imgData[index] }, // 获取最后一个图片 last: function() { index = len - 1 img.src = imgData[index] }, // 切换到前一张图片 pre: function() { if(--index >0) {img.src = imgData [index]} else {index = 0 img.src = imgData [index]}}, / / switch to the latter picture next: function () {if (+ + index)
< len) { img.src = imgData[index] }else { index = len - 1 img.src = imgData[index] } }, // 自动播放图片 play: function() { timer = setInterval(() =>{if (index > len-1) {index = 0} img.src = imgData [index] index++}, 5000)} / / stop playing pictures stop: function () {clearInterval (timer)} / / use let player = new imgPlayer (imgData,'# box')
In short, the combination of iterator ideas and other design patterns can design a variety of highly configured components, so learning and understanding the essence of javascript design patterns determines our height and attitude.
Thank you for reading, the above is the content of "how to use the iterator pattern", after the study of this article, I believe you have a deeper understanding of how to use the iterator pattern, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.