2013-03-22 4 views
1

У меня есть этот кофейник, который я получил от этого вопроса, который я задал ранее.Перерыв на цикл и результат возврата один раз найдено

window.getObject = (theObject, key, val) -> 
    result = null 
    if theObject instanceof Array 
    i = 0 
    while i < theObject.length 
     result = getObject(theObject[i], key, val) 
     i++ 
    else 
    for prop of theObject 
     return theObject if theObject[prop] is val if prop is key 
     result = getObject(theObject[prop], key, val) if theObject[prop] instanceof Object or theObject[prop] instanceof Array 
    result 

Он находит результат здесь:

return theObject if theObject[prop] is val if prop is key 

Теперь нужно остановить рекурсию и вернуться с результатом. Но он не вырвался из цикла и, таким образом, установил результат в null agian. Я уверен, что я пропустил что-то глупое!

EDIT

Теперь я изменился, так что я думаю, что это будет работать

window.getObject = (theObject, key, val) -> 
    result = null 
    if theObject instanceof Array 
    i = 0 
    while i < theObject.length 
     result = getObject(theObject[i], key, val) 
     i++ 
    else 
    for prop of theObject 
     if theObject[prop] is val and prop is key 
     result = theObject 
     console.log "I found it" 
     break 
     console.log "I must not log after found it was logged" 
     result = getObject(theObject[prop], key, val) if theObject[prop] instanceof Object or theObject[prop] instanceof Array 
    console.log "stop!!" 
    result 

Журнал выглядит в порядке:

I must not log after found it was logged ui.js:49 
I must not log after found it was logged ui.js:49 
I must not log after found it was logged ui.js:49 
stop!! ui.js:54 
stop!! ui.js:54 
I must not log after found it was logged ui.js:49 
I must not log after found it was logged ui.js:49 
I must not log after found it was logged ui.js:49 
I found it ui.js:46 
stop!! ui.js:54 
I must not log after found it was logged ui.js:49 
I must not log after found it was logged ui.js:49 
I must not log after found it was logged ui.js:49 
stop!! ui.js:54 
stop!! ui.js:54 
stop!! ui.js:54 
stop!! ui.js:54 
I must not log after found it was logged ui.js:49 
stop!! ui.js:54 
I must not log after found it was logged ui.js:49 
stop!! ui.js:54 
stop!! ui.js:54 
stop!! 
+0

Чтобы остановить цикл, используйте ключевое слово 'break' – George

+0

как это? если theObject [prop] имеет значение val , если prop является ключом return theObject break – Harry

+0

Если вы «возвращаете» из всей функции, вам не нужно «ломать» цикл – Bergi

ответ

1

Журнала правильно, показывая рекурсивные вызовы:

I must not log after found it was logged ui.js:49 
    I must not log after found it was logged ui.js:49 
     I must not log after found it was logged ui.js:49 
      stop!! ui.js:54 
     stop!! ui.js:54 
    I must not log after found it was logged ui.js:49 
     I must not log after found it was logged ui.js:49 
      I must not log after found it was logged ui.js:49 
       I found it ui.js:46 
       stop!! ui.js:54 
      I must not log after found it was logged ui.js:49 
       I must not log after found it was logged ui.js:49 
        I must not log after found it was logged ui.js:49 
        stop!! ui.js:54 
       stop!! ui.js:54 
      stop!! ui.js:54 
     stop!! ui.js:54 
    I must not log after found it was logged ui.js:49 
     stop!! ui.js:54 
    I must not log after found it was logged ui.js:49 
     stop!! ui.js:54 
    stop!! ui.js:54 
stop!! 

(игнорируя массив часть, после каждого «я не должен войти» еще один рекурсивный уровень называется, и каждый вызов заканчивается «Стоппы ")

Как вы можете видеть, после того, как« я нашел », цикл сразу же останавливается.

Буц не вырваться из петли и, таким образом, устанавливая результат обнулить agian

Это происходит на следующий более высокий уровень. Вы счастливо назначаете result = getObject(…), но здесь вы не нарушаете, если рекурсивный вызов привел к чему-то (то же самое в цикле массива).

Однако вместо поддержания result переменной я считаю рано возвращается легче читать (и вам не нужно break):

window.getObject = (theObject, key, val) -> 
    if theObject instanceof Array 
    for item in theObject 
     result = getObject(item, key, val) 
     return result if result 
    else 
    for prop, item of theObject 
     return theObject if item is val and prop is key 
     result = getObject(item, key, val) if item instanceof Object or item instanceof Array 
     return result if result 
    null 
+0

Shweeet, спасибо, человек! Это работает и выглядит намного лучше – Harry

0

Похоже, вам нужен еще один перерыв если результат не равен нулю. Что-то вроде этого:

result = getObject(theObject[prop], key, val) if theObject[prop] instanceof Object or theObject[prop] instanceof Array 
break if result not null 

Вам необходимо разбить свою петлю, если объект был найден внутри рекурсивного вызова этой функции.

Смежные вопросы