2014-12-15 14 views
6

Utilizzando il codice seguente, la funzione restituisce più volte. Devo interrompere la ricorsione e restituire il risultato solo una volta.Come interrompere e tornare dalle funzioni ricorsive?

Qualche idea su come risolverlo?

http://jsfiddle.net/xhe6h8f0/

var data = { 
    item: [{ 
     itemNested: [{ 
      itemNested2: [{ 
       id: "2" 
      }] 
     }] 
    }] 
}; 

function findById (obj, id) { 
     var result; 
     for (var p in obj) { 
      if (obj.id) { 
       if(obj.id == id) { 
        result = obj; 
        break; // PROBLEM HERE dos not break 
       } 
      } else { 
       if (typeof obj[p] === 'object') { 
        findById(obj[p], id); 
       } 
      } 
     } 
     console.log(result); 
     return result; 
} 
var result = findById(data, "2"); 
alert(result); 

risposta

8

Se viene trovata la corrispondenza, allora avete bisogno di restituire il valore. E nella chiamata genitore, se la chiamata ricorsiva restituisce un valore, allora deve anche restituire quel valore. È possibile modificare il codice come questo

function findById(obj, id) { 
    var result; 
    for (var p in obj) { 
     /* 
      if `id` is not in `obj`, then `obj.id` will evaluate to 
      be `undefined`, which will not be equal to the `id`. 
     */ 
     if (obj.id === id) { 
      return obj; 
     } else { 
      if (typeof obj[p] === 'object') { 
       result = findById(obj[p], id); 
       if (result) { 
        return result; 
       } 
      } 
     } 
    } 
    return result; 
} 

Ora,

var result = findById(data, "2"); 
console.log(result); 

stamperà

{ id: '2' } 
+0

perfetto. Grazie per l'aiuto – GibboK

Problemi correlati