gpt4 book ai didi

javascript - 如何创建和调用要在方法中调用的对象

转载 作者:行者123 更新时间:2023-11-29 11:00:42 25 4
gpt4 key购买 nike

在下面的代码中,我遍历了所有目录和任何扩展名为“js”的文件,我将其添加到“files_”数组。我还想做的是,创建一个对象或方法“accumulateData”,每次调用“files_.push”时都会更新该对象或方法。这样,对于每次迭代,调用“files_.push”,“accumulateData”将包含“files_.push”的最近/更新内容和总大小。

此外,我希望下面的方法返回“accumulateData”,以便在方法“getFiles”完成迭代后我可以调用类似的东西,

console.log(accumulateData.totalSize)

请告诉我如何实现这一目标

代码:

function getFiles(dir, files_) {
files_ = files_ || [];
var files = fs.readdirSync(dir);

for (var i in files) {
var name = dir + '/' + files[i];
if (fs.statSync(name).isDirectory()) {
getFiles(name, files_);
} else if (name.endsWith('js')) {
//totalSize += fs.statSync(name).size;
files_.push({ name: name, size: fs.statSync(name).size });
/*accumulateData(files, totalSize)
{
files = files;
totoalSize = totalSize;
}*/
}
}
return files_;
//return accumulateData
}

我的尝试

let totalSize = 0;
let accumulatedData;
function getFiles(dir, files_) {
files_ = files_ || [];
const files = fs.readdirSync(dir);

for (const i in files) {
const name = dir + '/' + files[i];
if (fs.statSync(name).isDirectory()) {
getFiles(name, files_);
} else if (name.endsWith('js')) {
// files_.push(name);

totalSize += fs.statSync(name).size;
files_.push({ name: name, size: fs.statSync(name).size });
// data(files, totalSize);

accumulatedData = {
files: files,
totalSize: totalSize
};
}
}
return accumulatedData;
}

console.log(getFiles('/home/bakria/Projects/smartvehicle').totalSize);

最佳答案

您可以使用包含文件数组和总大小的对象:

function getFiles(dir, obj) {
obj = obj || { files: [], totalSize: 0 }; // if no object is provided then initialize obj with an object that contains an empty array for files and 0 for totalSize
var files = fs.readdirSync(dir);
for(var i = 0; i < files.length; i++) {
var name = dir + '/' + files[i];
var stat = fs.statSync(name); // to minimize the calls to fs.statSync
if (stat.isDirectory()) {
getFiles(name, obj); // pass obj to getFile (recursion)
} else if (name.endsWith('js')) {
obj.totalSize += stat.size; // add this file's size to obj.totalSize
obj.files.push({ name: name, size: stat.size }); // push this file's object into obj.files
}
}
return obj; // return obj
}

返回将是这样的:

var result = getFiles("some/dir");

结果是:

{
files: [/* an array of files */],
totalSize: /* total size of the files */
}

因此 result.files 将是文件数组,result.totalSize 将是总大小。

关于javascript - 如何创建和调用要在方法中调用的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47638333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com