日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

js 用迭代器模式优雅的处理递归问题

發布時間:2023/12/9 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 用迭代器模式优雅的处理递归问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。