【问题标题】:Array of objects passed to function is empty传递给函数的对象数组为空
【发布时间】:2020-04-27 23:06:47
【问题描述】:

用 typescript 编写的 Ionic 应用程序:

 let files: any[] = [];
 files =this.getFiles("wildlife");
 console.log("files:", files);
  this.render(files); 

这个输出说

这很奇怪,因为虽然那里有 50 个项目,但它显示 Array(0)。 问题是当我在函数中传递这个数组时:

  render( files) 
    {
     files.forEach(item => {
    console.log(item) <- does not exist

    });
    }

数组为空。这是为什么 ? 还有其他方法可以传递数组并循环其对象吗?

编辑:

getFiles(folder) {
    let files: any[] = [];

    this.file.listDir(this.file.applicationDirectory, 'www/assets/' + folder)
      .then((items) => {
        // console.log(items);

        items.forEach(item => {
          files.push({
            filename: item.name,
            name: this.getName( item.name)
          });
        });
      })
      .catch(err =>
        console.log("error: ", err));

    return files;
  }

【问题讨论】:

  • 你不能在没有async的情况下使用await 将你的代码包装在函数中标记函数异步
  • getFiles 是什么样子的?
  • 我猜你正试图在它们实际存在之前将它们记录到渲染函数中。你可能没有像你应该的那样使用异步等待。您能否发布更多代码,以便我们看到更大的图景。
  • 请忽略 async/await 关键字。我试过了,没有
  • 我怀疑你是 not properly returning some async response 而你是 looking at this in the browser console which is lazy about evaluating objects 所以当你登录时 files它是一个空数组但是当你展开它时(不同的时间点),它现在已填充。这里的代码不足以说明如何修复它,但请查看我的第一个链接。

标签: javascript arrays typescript for-loop foreach


【解决方案1】:

您需要将getFiles 函数调用为异步函数。

let files: any[] = [];
 this.getFiles("wildlife")
   .then(res => {
     files = res;
     console.log("files:", files);
     this.render(files);
 }); 

【讨论】:

    猜你喜欢
    • 2020-12-22
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多