typescript - Foreach 数组以在 TypeScript 中显示值

标签 typescript loops pdf

我正在尝试创建一个 PDF,其中的数据是从数据库中获取的。以下是我在 TypeScript 中进行变量声明的方式。

essay = {
    "title": "",
    "author": { "fullname": "" },
    "intro": "",
    "conclusion": "",
    "paragraphs": [ { "paragraph": "" } ]
}

正如你在这里看到的,段落是数组类型的。因此,当触发生成 PDF 的按钮时,将调用下面的函数。

CreatePdf(){
    var docDefinition = {
      content: [
        { text: this.essay.title, style: 'header' },
        { text: new Date().toTimeString(), alignment: 'right' },

        { text: 'Written By : '+this.essay.author.fullname, style: 'subheader' },

        { text: this.essay.intro, style: 'story', margin: [0, 20, 0, 20] },

        // Foreach essay.paragraphs and display the value

        { text: this.essay.conclusion, style: 'story', margin: [0, 20, 0, 20] }
      ]
    }
    this.pdfObj = pdfMake.createPdf(docDefinition);
    this.pdfObj.download();
}

问题是,我要如何执行 foreach 以显示 content:[] 中的所有段落值?我正在尝试在内容中应用以下循环,但做不到。

for(let parag of this.essay.paragraphs){
  console.log(parag.paragraph);
};

最佳答案

您可以使用 ... 运算符和 map() 来实现:

CreatePdf(){
    var docDefinition = {
      content: [
        { text: this.essay.title, style: 'header' },
        { text: new Date().toTimeString(), alignment: 'right' },

        { text: 'Written By : '+this.essay.author.fullname, style: 'subheader' },

        { text: this.essay.intro, style: 'story', margin: [0, 20, 0, 20] },

        ...this.essasy.paragraphs.map( p => {
            return {text: p.paragraph, style: 'story', margin: [0, 20, 0, 20]};
        }),

        { text: this.essay.conclusion, style: 'story', margin: [0, 20, 0, 20] }

      ]
    }
    this.pdfObj = pdfMake.createPdf(docDefinition);
    this.pdfObj.download();
}

map() 顾名思义,使用给定的函数映射每个元素,... 只是将数组展平。

关于typescript - Foreach 数组以在 TypeScript 中显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50904395/

相关文章:

ios - 如何在 Objective C 的循环中为按钮重复动画?

java - 有没有更快的方法根据值排列数字?

SQL Server : Endless WHILE EXISTS loop

javascript - 如何在现有 PDF 中嵌入并执行 JavaScript?

javascript - 单元测试未定义不是一个对象(评估 'this.groups.map' )

javascript - 为什么需要在 RxJs 中导入运算符?

javascript - 将 GeoFire 与 Firebase 9.17.1 一起使用时出现类型错误 : "t.split is not a function"

arrays - 如何在 Angular 2 中使用 TypeScript 过滤数组?

mysql - 从 MySQL 数据生成 PDF 并使用 Postfix 发送它,而不使用 PHP?

Java 屏幕截图应用程序 - 如何?