js 用迭代器模式优雅的处理递归问题
生活随笔
收集整理的這篇文章主要介紹了
js 用迭代器模式优雅的处理递归问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
什么是迭代器
循環數組或對象內每一項值,在 js 里原生已經提供了一個迭代器。
var arr = [1, 2, 3] arr.forEach(function (item) {console.log(item) })實現一個迭代器
var iterator = function (arr, cb) {for (let i = 0; i < arr.length; i++) {cb.call(arr[i], arr[i], i)} }var cb = function (item, index) {console.log('item is %o', item)console.log('index is %o', index) }var arr = [1, 2, 3] iterator(arr, cb)/* 打印: item is 1 index is 0 item is 2 index is 1 item is 3 index is 2 */實際應用
需求:
- Antd 的嵌套表格組件的數據源有要求,如果沒有子元素,children 屬性應該設置為 null 或者刪除 children 屬性,實際開發中后端返回的接口卻是沒有子元素時,children 屬性設置為一個空數組;
- 后端返回的字段名 categoryId 字段名更改為 value,name 字段名更改為 label。
數據結構修改前后示例。
var categoryList = [{categoryId: 1,name: '1級',children: [{categoryId: 11,name: '11級',children: [],},],},{categoryId: 2,name: '2級',children: []} ]// 處理之后數據結構如下var categoryList = [{value: 1,label: '1級',children: [{value: 11,label: '11級',},],},{value: 2,label: '2級',} ]使用迭代器模式優雅的處理遞歸類問題。
// 數據源 var categoryList = [{categoryId: 1,name: '1級',children: [{categoryId: 11,name: '11級',children: [],},],},{categoryId: 2,name: '2級',children: []} ]// 迭代器 var iterator = function (arr, cb) {for (let i = 0; i < arr.length; i++) {cb.call(arr[i], arr[i])} }// 處理每一項 var changeItem = function (item) {// 更改字段名稱item.value = item.categoryIditem.label = item.namedelete item.categoryIddelete item.name// 當 children 為空數組時,刪除 children 屬性if (item.children == false) {delete item.children} else {iterator(item.children, changeItem)} }// 調用迭代器 iterator(categoryList, changeItem) console.log(JSON.stringify(categoryList, null, 4))/* 打印: [{"children": [{"value": 11,"label": "11級"}],"value": 1,"label": "1級"},{"value": 2,"label": "2級"} ] */總結
凡是需要用到遞歸的函數參考迭代器模式,能寫出更優雅,可讀性更高的代碼。
轉載于:https://my.oschina.net/dkvirus/blog/3031505
總結
以上是生活随笔為你收集整理的js 用迭代器模式优雅的处理递归问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端学习(3237):react生命周期
- 下一篇: dea文件在线预览