首页 > 解决方案 > 存储多个字符串数组并将其显示在 html 中的最佳方式

问题描述

抱歉标题不好....我不知道如何命名。我有一个小问题。我有一个字符串数组,我想把这些字符串切成更小的部分。我使用循环和拆分方法来做到这一点。但是 split 也返回一个数组。

存储这些返回的数组的最佳方法是什么,以便我以后可以在我的 html 文件的表格中显示它?

我希望我的代码片段会更清楚。

books: string[];
booksDetails: string[][];
...
...
for (var i = 0; i < books.length ; i++) {
  var bookSplit = books[i].split(/(?:\/|-)+/);
  this.booksDetails.push(bookSplit);
}
...

然后显示它

<table>
  <thead>
    <tr>
      <th>name</th>
      <th>author</th>
      <th>date</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let book of booksDetails; let i = index" [attr.data-index]="i">
      <td>{{book[i][0]}}</td>
      <td>{{book[i][1]}}</td>
      <td>{{book[i][2]}}</td>
    </tr>
  </tbody>
</table>

标签: angularjstypescript

解决方案


您已经完成了一半,只需在元素上嵌套另一个ngFor-loop :<td>

...
<tr *ngFor="let book of booksDetails; let i = index" [attr.data-index]="i">
  <td *ngFor="let detail of book; let j = index" [attr.data-index]="j">
    {{detail}}
  </td>
</tr>
...

编辑:您也可以使用Array.map()代替冗长且不必要的 for 循环:

this.booksDetails = this.books.map(b => b.split(/(?:\/|-)+/));

推荐阅读