Nodejs Google Drive API - 在回调函数中访问数组元素

Nodejs Google Drive API - Accessing array elements in callback function

我希望使用 drive.files.list 生成的文件名用作下载文件夹中所有文件的字符串。

我在访问一组文件名时遇到问题。基本上是由于缺乏知识,所以我迷失了鼠标悬停在 files.map() 中引用 map 的逻辑,请参见下面的代码。

我的代码:

if (files.length) {
      // map method calls the callbackfn one time for each element in the array 
      files.map((file) => {     
      // there are x elements (a filename/id) called x times     

  // I want to access one filename at a time. Return a plain string filename for a downloadFile() function    
        var names = [];    
      
  //  rough test to produce desired output. Produces 'undefined' for array indexes greater than 0 e.g names[1]
  //      files.length = 1; 

  // Without the files.length = 1; filename is outputted x times 
        var names = [];    
        files.forEach(function (file, i) {
          names[i]= file.name;
      })
// first array index (with files.length =1;) first filename and only this filename. Correct result!!! 
      console.log(names[0]);

我对 OOP 或 Nodejs 经验不多。但是使用各种测试(代码更改),最大的输出看起来像一个数组数组。我想将它缩小到一个文件名数组,我可以 JSON.stringify 在用于下载之前。

鼠标悬停在 'map'

(method) Array<drive_v3.Schema$File>.map<void>(callbackfn: (value: drive_v3.Schema$File, index: number, array: drive_v3.Schema$File[]) => void, thisArg?: any): void[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param callbackfn — A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param thisArg — An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

感谢任何建议。

尝试用这个替换代码:

if (files.length) {

  var names = [];
  files.forEach(function(file, i) {
    names.push(file.name);
  });

  console.log('filenames: ', names);
}

然后可以通过names数组循环读取文件名,传递给其他函数处理:

names.forEach((fileName, i)=>{
  console.log('filename: ', fileName, ' index', i);
  // pass the name to other functions for processing
  download(fileName);
});