在遍历整个树之前,Javascript递归是否完成? [英] Javascript recursion completes before traversing the whole tree?
问题描述
我正在开展一个项目,其中一个练习要求遍历下面的数据结构并返回包含所有文件的数组(即* .js,* .css):
I'm working on a project where one exercise asks to traverse a data structure below and returning an array containing all the files (i.e. *.js, *.css):
var fileData = {
dir : 'app',
files : [
'index.html',
{
dir : 'js',
files: [
'main.js',
'app.js',
'misc.js',
{
dir : 'vendor',
files : [
'jquery.js',
'underscore.js'
]
}
]
},
{
dir : 'css',
files : [
'reset.css',
'main.css'
]
}
]
};
我想出了一个递归解决方案,这样当你调用 listFiles
参数 fileData
它应该返回所需的数组:
I came up with a recursive solution so that when you call listFiles
with parameter fileData
it should return the desired array:
function listFiles(data) {
var retval = [];
var files;
(function crawl(filedata) {
files = filedata.files;
if (typeof files !== 'undefined') {
for (var i = 0; i < files.length; i++) {
if (typeof files[i] === 'string') {
retval.push(files[i]);
} else {
crawl(files[i]);
}
}
}
})(data);
return retval;
}
但是,在运行代码时,它只返回* .js。这意味着在目录 app
中,我的程序应该遍历所有三个元素但是在第二个递归调用之后它不会检查第三个(/ css)。有谁能解释为什么?非常感谢!
However, when running the code it only returns *.js. This means in directory app
, my program is supposed to traverse all three elements but after the recursive call on the second it does not go check the third (/css). Can anyone explain why? Thanks a lot!
推荐答案
您需要将文件
变量置于本地到递归函数。否则,当您递归时,您将覆盖调用者中使用的值。
You need to make the files
variable local to the recursive function. Otherwise, when you recurse, you're overwriting the value used in the caller.
function listFiles(data) {
var retval = [];
(function crawl(filedata) {
var files = filedata.files;
if (typeof files !== 'undefined') {
for (var i = 0; i < files.length; i++) {
if (typeof files[i] === 'string') {
retval.push(files[i]);
} else {
crawl(files[i]);
}
}
}
})(data);
return retval;
}
这篇关于在遍历整个树之前,Javascript递归是否完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!