我正在努力如何增加javascript中的基本计数器。
我需要一个foreach
循环内的计数器。目的是能够在每次//Write smthg
触发时进行计数。
以下是我正在使用的代码的更新版本。目前,它返回奇怪的数字序列。我想每次触发递归循环都会重置它。我不知道如何纠正它,这是一个基本的javascript问题,但是当我通过实验和自己学习时,有时我需要向社区提出问题。
function walk(dir, counter = 0) {
fs.readdirSync(dir).forEach(file => {
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
counter = walk(fullPath, counter);
walk(fullPath, counter);
console.log('dir');
} else {
let size = fs.statSync(fullPath).size; // Get size of file
listFiles.write(fullPath + " (" + size + ")\n"); // Write file path and size into copyList.xml
++counter;
console.log(counter);
}
});
return counter;
}
walk(copyFrom); // Starts function "walk"
获得的序列:
2,3,4,5,6,7,dir,5,6,8,9,10,11,12,13,dir,11
function walk(dir) {
let n = 0;
function walk(dir) {
fs.readdirSync(dir).forEach(file => {
++n;
console.log(n);
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
--n;
walk(fullPath);
console.log('dir');
} else {
let size = fs.statSync(fullPath).size; // Get size of file
listFiles.write(fullPath + " (" + size + ")\n"); // Write file path and size into copyList.xml
}
});
}
return walk(dir);
}
使用助手。该函数walk
生成词法变量,n
并walk
在递归调用期间隐藏被调用函数。它可能具有的原始内容,walk
并且外部函数只是返回调用它本身的结果。
function walk(dir) {
let n = 0; //Counter variable
function walk(dir) {
dir.forEach(file => {
++n;
console.log(n);
if (true) {
//Recurse loop
} else {
//Write smthg
}
});
}
return walk(dir);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句