我有這個咖啡的腳本,我從這個問題,我問得更早。打破循環並返回結果一旦找到
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
現在需要停止遞歸,並返回結果。但它不會擺脫循環,因此將結果設置爲空agian。我確定我錯過了一些愚蠢的東西!
編輯
現在我改變了,所以我會認爲這會工作
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 2013-03-22 10:14:57
這樣嗎?如果對象[prop]是val 如果prop是關鍵 return theObject break – Harry 2013-03-22 10:16:05
如果你從整個函數中執行'return',則不需要'循環'循環 – Bergi 2013-03-22 10:24:45