0

I would like to improve this for loop. Ideally I do not want the variable 'nodeFound' outside the function scope and I would like to return the 'nodeFound' as soon as it is found not after the loop has completed.

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;
};
4

3 回答 3

0

Use 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;
};
于 2013-07-19T09:30:18.960 回答
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;
};
于 2013-07-19T09:36:57.133 回答
0

If you store your data in a JSON object, you won't need a loop. And so your performance will increase a lot.

But you need to change your data format ...

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': {
          ...
        }
      }
    }
}

After, the code look like this

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;
};

Does it helps ?

于 2013-07-19T09:38:18.547 回答