以下函数将一个对象追加到嵌套数组中(通过递归搜索它):
function appendDeep (arr, obj, newObj) {
if (arr.indexOf(obj) !== -1) {
arr.splice(arr.indexOf(obj) + 1, 0, newObj)
} else {
arr.map(item => {
if (item.children) spliceDeep(item.children, obj)
})
}
}
示例:
const colors = {
children: [
{
name: 'white',
},
{
name: 'yellow',
children: [
{
name: 'black'
}
]
}
]
}
const color = {
name: 'black'
}
const newColor = {
name: 'brown'
}
appendDeep(colors.children, color, newColor)
结果:
children: [
[
{
name: 'white',
},
{
name: 'yellow',
children: [
{
name: 'black'
},
{
name: 'brown'
}
]
}
]
]
如您所见,appendDeep
返回一个副作用;它修改arr
。所以我决定返回数组(这样函数就会变得纯):
function findDeep (arr, obj) {
if (arr.indexOf(obj) !== -1) {
console.log(arr)
return arr
} else {
arr.map(item => {
if (item.children) findDeep(item.children, obj)
})
}
}
并像这样使用新函数:
const newArr = findDeep(colors.children, color)
newArr.splice(newArr.indexOf(color) + 1, 0, newColor)
但我收到此错误:
bundle.js:19893 Uncaught TypeError: Cannot read property 'splice' of undefined
我做错了什么?
(注意:这是 CodePen 。)
(注 2:console.log(arr)
确实返回嵌套的子级。但由于某种原因,它们在函数外部变为 未定义
。)
最佳答案
您不会在 map
中返回递归 findDeep
方法。返回该递归以使递归起作用,因为您的条件分支没有从映射内返回任何内容。因此,您得到的结果为 undefined
。 JSBin
关于javascript - 如何将以下递归函数变成纯函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36661329/