什么是迭代器
循环数组或对象内每一项值,在 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 () {
}
var arr = [1, 2, 3]
iterator(arr, function (item, index) {
console.log('item is %o', item)
console.log('index is %o', index)
})
/*
打印:
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.categoryId
item.label = item.name
delete item.categoryId
delete item.name
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级"
}
]
*/
总结
凡是需要用到递归的函数参考迭代器模式,能写出更优雅,可读性更高的代码。