當變量指向一個對象的時候,實際指向的是存儲地址
測試:node
a = {val: 123} b = a b.val = 321 console.log(a) // 結果:{val: 321}
數組轉樹的方式:數組
arr = [ {id: 1, name: '節點1', pid: 0}, {id: 2, name: '節點2', pid: 1}, {id: 3, name: '節點3', pid: 1}, {id: 4, name: '節點4', pid: 2}, {id: 5, name: '節點5', pid: 1}, {id: 6, name: '節點6', pid: 3}, {id: 7, name: '節點7', pid: 4}, {id: 8, name: '節點8', pid: 2} ]; function node(d){ return { name: d.name, id: d.id, pid: d.pid, children: [] } } function tree(arr){ var narr = {}; for (var i in arr) { // 將id做爲鍵值方便二次遍歷作索引 narr[arr[i].id] = node(arr[i]); } for (var j in narr) { if(typeof narr[narr[j].pid] != 'undefined'){ narr[narr[j].pid].children.push(narr[j]) } } return narr[1] // id爲1的是根節點 } console.log(tree(arr))
這樣只要遍歷倆次
第一次遍歷將數組轉節點對象,存儲到新的對象裏,id爲鍵值方便索引
第二次遍歷根據索引插入子節點測試