我在遞回函式中遇到了一個非常奇怪的問題。我的代碼如下:
tree_generator(startNode, dictionary) {
let resultNode = startNode
// find node name from dictionary
let hasChild = dictionary[resultNode.name]
? dictionary[resultNode.name].parts.length > 0
? true
: false
: false
if (hasChild) {
//create child node object
let children = _.map(dictionary[resultNode.name].parts, item => {
let childpart = {
id: 'd_' item.name,
name: item.name,
children: [],
ontology_name: item.partIri.replace(/.*otl\//, '') // need to update to related uri value
}
this.level = this.level 1
// recurve to get the result for child node
this.tree_generator(childpart, dictionary)
return childpart
})
console.log('real child')
console.log(children)
resultNode.children = children
console.log('real result node in tree')
console.log(resultNode)
} else {
//it is a leaf, delete child node
delete resultNode.children
}
return resultNode
}
當我傳遞不同的字典引數時,回傳結果應該不同,但實際上,它總是回傳與最后一個字典值相同的結果。
當我控制臺記錄孩子和resultNode值時,孩子的值總是正確的字典,但 resultNode 總是分配一個與真正孩子不同的值。
有誰知道我在這里做錯了什么?
測驗資料組:group1:startNode:
{
id: '0_d_TestOne',
name: 'TestOne',
children: [],
ontology_name: 'testOne'
}
字典:
{
TestOne: { uri: 'TestOne', parts: [{ name: 'testTwee', partIri: 'http://otl/testTee' }] },
testTwee: { uri: 'testTwee', parts: [{ name: 'testDrie', partIri: 'http://otl/testDrie' }] },
testDrie: { uri: 'testDrie', parts: [{ name: 'testVier', partIri: 'http://otl/testVier' }] },
testVier: { uri: 'testVier', parts: [{ name: 'TestVijf', partIri: 'http://otl/TestVijf' }] }
}
組2:開始節點:
{
id: '0_d_TestOne',
name: 'TestOne',
children: [],
ontology_name: 'testOne'
}
字典:
{
TestOne: { uri: 'TestOne', parts: [{ name: 'TestTwo', partIri: 'http://otl/TestTwo' }] },
TestTwo: { uri: 'TestTwo', parts: [{ name: 'TestThree', partIri: 'http://otl/TestThree' }] },
TestThree: {
uri: 'TestThree',
parts: [{ name: 'TestFour', partIri: 'http://otl/TestFour' }]
},
TestFour: { uri: 'TestFour', parts: [{ name: 'TestFive', partIri: 'http://otl/TestFive' }] }
}
起始節點相同,字典不同,預期的樹輸出應該不同
uj5u.com熱心網友回復:
起始節點相同,預期的樹輸出應該不同
你的問題是:你的函式不會創建新的輸出,它會修改startNode你傳入的輸出。如果你用不同的字典兩次傳入同一個物件,只有最后一次呼叫的結果會存盤在你的物件中。
我建議不要傳入物件,而只傳入要從字典中獲取的樹節點的名稱,并且始終創建一個新的結果物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/417793.html
標籤:
上一篇:將遞回轉化為迭代
