[{num:1,child:[{num:1,child: [{num: 1,}]}]}]有一个类似这种结构的数组,我要改变最里面一层的num增加1,我需要让往上的每一层的num值对应增加1,求问该怎么写最方便而且我的数据层级数不确定,有可能三层有可能两层,最多四层,并且我还同时需要去减少num,减少最外层的num内层也会改变。现在困在这个问题很久了 希望能求个帮助
调试欢乐多
function count(arr){
if(Array.isArray(arr)){
arr.forEach(function(o){
if(o.child){
count(o.child)
o.num = o.child.reduce(function(c,v){
return c + v.num
},0)
}
})
}
}
// 减少后赋值
function reduce(child,sum){
if(Array.isArray(child)){
child.forEach(function(o){
var _sum = sum
sum -= o.num
if(Number.isInteger(sum) && sum < 0){
o.num = _sum
sum = 0
}
reduce(o.child,o.num)
})
}
}
count(json)
console.log(JSON.stringify(json))
json[1].num = 20
reduce(json)
console.log(JSON.stringify(json))