2013-07-19 77 views
0

我想改善這個循環。理想情況下,我不想在函數範圍之外使用變量'nodeFound',並且我希望在循環完成後立即返回'nodeFound'。我怎樣才能使這個循環更高性能

var nodeFound; 
proto._getNodeById = function(id, node) { 
    var data = node || this._data; 
    var l = data.length; 
    var i; 

    for (i = 0; i < l; i++) { 
     if (Number(id) === data[i].id) { 
      nodeFound = data[i]; 
     } else { 
      if (data[i].children.length) { 
       this._getNodeById(id, data[i].children); 
      } 
     } 
    } 
    return nodeFound; 
}; 
+2

這不是要求這種事情的網站。請訪問:http://codereview.stackexchange.com/ – Bloodcount

+1

如果您希望在找到節點時立即打破環路,只需將nodeFound指定爲期望值並「斷開」即可。循環 –

回答

0
proto._getNodeById = function(id, node) { 

    var data = node || this._data; 
    var thisNode = null; 
    var l = data.length; 
    var i; 

    id=+id; // convert to number 

    for (i = 0; i < l; i++) { 
     thisNode = data[i] ; 
     if (id === thisNode.id) { 
      return thisNode; 
     } else if (thisNode.children.length) { 
      thisNode = this._getNodeById(id, thisNode.children); 
      if (thisNode) return thisNode; 
     }   
    } 
    return null; 
}; 
+0

很好,謝謝 – user1812741

0

使用while

proto._getNodeById = function(id, node) { 
    var data = node || this._data; 
    var l = data.length; 
    var i=0; 
    var found = false; 
    var nodeFound = undefined; 

    while (i < l && !found) { 
     if (Number(id) === data[i].id) { 
      nodeFound = data[i]; 
      found = true 
     } else { 
      if (data[i].children.length) { 
       var node = this._getNodeById(id, data[i].children); 
       if (node != undefined) { 
        nodeFound = node; 
        found = true; 
       } 
      } 
     } 
     i++; 
    } 
    return nodeFound; 
}; 
+0

這並不能解決我的問題,因爲它在放入else語句時迭代自身,並且nodeFound被設置爲false。 – user1812741

+0

現在我明白了。我沒有注意到它是遞歸的。固定我認爲:) – nathanvda

0

如果你存儲在一個JSON對象你的數據,你會不會需要一個循環。 所以你的表現會增加很多。

但是,你需要改變你的數據格式...

data = { 
    'id1': { 
    'property1': 'value', 
    'property2': 'value', 
    'property3': 'value', 
    'children': { 
     'property1': 'value', 
     'property2': 'value', 
     'property3': 'value', 
     'id2': { 
     'children': { 
      ... 
     } 
     }, 
     'id3': { 
     'property1': 'value', 
     'property2': 'value', 
     'property3': 'value', 
     'children': { 
      ... 
     } 
     } 
    } 
} 

後,代碼看起來象

proto._getNodeById = function(id, node) { 
    var data = node || this._data; 

    if(data[id] !== undefined) { 
    nodeFound = data[id]; 
    } 
    else if (data[id] && data[id].children) { 
    this._getNodeById(id, data[id].children); 
    } 

    return nodeFound; 
}; 

它可以幫助?