2014-11-02 40 views
0

以下是兩個工作版本(用於Node.js)的相同遞歸函數。遞歸沒有顯式設置變量javascript

1版

function getDependencies(mod, result) { 
    result = result || [] 
    var dependencies = mod.dependencies || [] 
    Object.keys(dependencies).forEach(function(dep) { 
    var key = dep + '@' + mod.dependencies[dep].version 
    if (result.indexOf(key) === -1) result.push(key) 
    getDependencies(mod.dependencies[dep], result) // COMPARE THIS LINE 
    }) 
    return result.sort() 
} 

2版

function getDependencies(mod, result) { 
    result = result || [] 
    var dependencies = mod.dependencies || [] 
    Object.keys(dependencies).forEach(function(dep) { 
    var key = dep + '@' + mod.dependencies[dep].version 
    if (result.indexOf(key) === -1) result.push(key) 
    result = getDependencies(mod.dependencies[dep], result) // COMPARE THIS LINE 
    }) 
    return result.sort() 
} 

如何函數工作1版本相比,2.0版本,但沒有明確設定結果變量?

+0

你的分號鑰匙壞了嗎? – jfriend00 2014-11-02 06:17:06

+0

這是來自Nodeschool的Node.js解決方案。 – user3477405 2014-11-02 06:17:58

回答

1

result.push(key)result.sort()都修改作爲參數傳入的result數組。所以不需要在調用者中再次分配它。

+0

那麼它是否因參考傳遞而改變?如果getDepenencies()遞歸調用多次,我不明白結果如何「加起來」並最終作爲一個值返回。 – user3477405 2014-11-02 06:22:47

+0

當您傳遞或分配對象或數組時,您將獲得對同一對象/數組的引用,但它不會創建副本。所以所有的遞歸調用都在同一個'result'數組上運行。 – Barmar 2014-11-02 06:24:56

+0

@ user3477405 - 只有一個數組。當你將它傳遞給一個函數時,不會創建副本 - 它是相同的數組。所以,如果一個函數修改它,原始的被修改。無需返回它。它在技術上不是通過引用傳遞,更像是通過指針傳遞。 – jfriend00 2014-11-02 06:25:32