我第一次尝试递归地遍历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