私は以前に尋ねたこの質問から得たこのコーヒースクリプトを持っています。
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
ここで、再帰を停止して結果を返す必要があります。しかし、それはループから抜け出さないため、結果をnullagianに設定します。確かに私は愚かな何かを逃しています!
編集
今私はこれがうまくいくと思うように変更しました
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!!