各位大佬,针对这个问题我是这么写的代码?请问有没有什么问题?
一般你们会怎么写更好
let obj = {
name:'a',
child:[{
name:'b',
child:[{
name:'c',
child:[]
},{
name:'d',
child:[]
},{
name:'b1',
child:[{
name:'c2',
child:[]
},{
name:'d3',
child:[]
}]
}]
}]
}
function getName(obj){
let arr = [];
getData(obj)
function getData(obj) {
if (Object.prototype.toString.call(obj) == '[object Object]') {
arr.push(obj.name)
if (obj.child.length) {
getData(obj.child)
}
} else if (Object.prototype.toString.call(obj) == '[object Array]') {
obj.forEach((item)=>{
arr.push(item.name)
if (item.child.length) {
getData(item.child)
}
})
}
return arr;
}
return arr;
}
console.log(getName(obj))