我想創建一個函數,它將生成一個像結構這樣的樹,以便每個項目包含對它的父項目的引用。Javascript遞歸函數參考這個
我有一個函數可以在創建孩子時調用自己,但是對它有困難的時候,似乎一旦從它自己內部調用它,this
仍然指向頂級項目而不是當前項目。
記錄控制項目是什麼我可以看到,父母始終指的是鏈中的第一項(或缺席)比第一級更深。它創建樹,但除了第一個項目之外,對父項的引用會丟失。
var Item = function (item, parent) {
console.log('item is :' + item.name);
this.parent = parent;
console.log('parent is: ' + parent);
var fields = _.union(_.keys(item), _.keys(this.parent));
_.each(_.without(fields, ['parent','children']), function (prop) {
this[prop] = angular.isDefined(item[prop]) ? item[prop] : this.parent[prop];
}, this);
this.children = [];
if (item.children) {
this.children = _.map(item.children, function (child) {
console.log('this is : ' + this);
return new Item(child, this)
}, this);
}
};
var tree = new Item(root, {});
有一點麻煩小提琴去,但這裏是一些樣本數據:
var root = JSON.parse('{"id":"1","name":"root item","root":"1","lft":"1","rgt":"22","level":"1","type":
"category","parent_id":"1","deadline":null,
"children":[
{"id":"2","name":"item 1","root":"1","lft":"14","rgt":"15","level":"2","type":"category","parent_id":"1"},
{"id":"6","name":"item 2","root":"1","lft":"16","rgt":"19","level":"2","type":"category","parent_id":"1"},
{"id":"10","name":"item 3","root":"1","lft":"20","rgt":"21","level":"2","type":"item","parent_id":"1"}]}');
只是一個錯字,我一直在試驗,並忘記修改之前發佈。修正它在這裏,問題仍然是一樣的。 – JPR
你可以用一些虛擬數據爲此創建小提琴嗎? –
當然,可能需要幾分鐘才能把它放在一起。謝謝。 – JPR