簡體   English   中英

如何將array.map與二維數組一起使用

[英]How to use array.map with a 2-dimensional array

我需要遍歷一個數組,但該語句位於方括號[]之間

但是,不允許在括號之間放置for語句,因此將導致SyntaxError: missing 'of' after for

在互聯網上搜索時,我發現array.map()可能是一種解決方案。 但是,我找不到多維數組上array.map的示例,也無法使我的代碼正常工作。

下面的示例創建一個表並將其導出到pdf文件。 這可以正常工作,但僅適用於靜態表:

var docDefinition = {
content: [
{
  table: {
    body: [
      [ 'First', 'Second', 'Third', 'The last one' ],
      [ 'Value 1', 'Value 2', 'Value 3', 'Value 4' ],
      [ 'Val 1', 'Val 2', 'Val 3', 'Val 4' ]
    ]
  }
}
]};

JSFiddle

我需要用於動態表的代碼。 我正在嘗試從數組創建表,無法使其正常工作。 這是我到目前為止的內容:

function html2Pdf(){
var arr = [[ 'First', 'Second', 'Third', 'The last one' ],[ 'Value 1', 'Value 2', 'Value 3', 'Value 4' ],[ { text: 'Bold value', bold: true }, 'Val 2', 'Val 3', 'Val 4' ]];    
var docDefinition = {
content: [
{
  table: {
    body: [
     arr.map(function(item){
        return item
     })    
    ]
  }
}
]
};
pdfMake.createPdf(docDefinition).open();
}

JSFiddle

如前所述,可以將給定數組直接注入到結果結構中。

table: {
    body: arr
  }

關於您如何在二維數組上使用數組映射的問題:您可以像使用for循環或類似方法一樣完全嵌套它。

body: arr.map( function( row ) {
    return row.map( function( cell ) { 
        return foo( cell ); 
    } );
} )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM