У меня есть этот кофейник, который я получил от этого вопроса, который я задал ранее.Перерыв на цикл и результат возврата один раз найдено
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!!
Чтобы остановить цикл, используйте ключевое слово 'break' – George
как это? если theObject [prop] имеет значение val , если prop является ключом return theObject break – Harry
Если вы «возвращаете» из всей функции, вам не нужно «ломать» цикл – Bergi