需求:遞歸遍歷arr,給name名稱后面加上后綴“---111”,直到children下沒有children為止
原數組:
遍歷后數組:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>遞歸遍歷children</title> </head> <script src="js/jquery-3.1.1.min.js"></script> <body> </body> <script> let arr = [{ name: 'test1' },{ name: 'test2', children: [{ name: 'test2-1' }] },{ name: 'test3', children: [{ name: 'test1-1', children: [{ name: 'test2-1-1' }] }] }] calleArr(arr); function calleArr(array){ for(i in array){ var data=array[i]; if(data.children){ data.name=data.name+"--111"; calleArr(data.children) //自己調用自己 }else{ data.name=data.name+"--111"; } } } console.log(arr); </script> </html>