【发布时间】:2015-10-07 06:59:38
【问题描述】:
我第一次尝试以递归方式浏览 JSON 对象,并且通过调试器运行时的代码似乎可以正常工作,直到当我找到我正在寻找的 groupId 时它尝试返回该对象。这是我得到的错误:
Uncaught SyntaxError: Illegal return statement
at Object.InjectedScript._evaluateOn (<anonymous>:895:55)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
at Object.InjectedScript.evaluateOnCallFrame (<anonymous>:954:21)
at findGroupId (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:503:21)
at findGroupId (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32)
at findGroupId (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32)
at findGroupId (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32)
at findGroupId (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32)
at findGroupId (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32)
at findGroupId (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32)
请随意批评它的任何部分,因为这是我第一次尝试这样做。 :)
我的示例代码如下:
'use strict';
var findGroupId = function (obj, id) {
var checkForId = function (key, obj) {
if (key == id) {
return true;
}
return false;
};
if (typeof obj === 'object') {
for (var i in obj) {
if (typeof obj[i] === 'object') {
findGroupId(obj[i], id);
} else if (Array.isArray(obj[i])) {
for (var x = 0 ; x <= obj[i].length ; x++) {
findGroupId(obj[i], id);
}
} else {
var result = checkForId(obj[i], obj);
if (result) {
debugger;
return obj;
}
}
}
}
};
var result = findGroupId(obj, "37078;1");
console.log(result);
这是一个可执行的例子: http://codepen.io/eaglejs/pen/vOaZgd
感谢 Pablo,这是固定的解决方案: http://codepen.io/eaglejs/pen/QbBKGK
【问题讨论】:
-
在您的实际环境中,您是否将其视为承诺?我认为 async 可能会咬你的尾巴。
-
在我的环境中,它不是一个promise,它只是作为一个方法写在我的集合(骨干)中。我一直被教导异步编码,我想我什至不知道如何同步编码哈哈。我应该使用 try/catch 或类似的东西吗? :)
-
我把调试器放在你可以在控制台中调用“return obj”的地方,你会看到错误。即使使用“use strict”,它也会默默地失败。
标签: javascript json recursion traversal