我有这个咖啡脚本,我从我之前问过的这个问题中得到的。
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!!