簡體   English   中英

使用單個數組角度組件顯示矩陣

[英]Show a matrix using a single array angular component.html

我有一個數組,假設[1,2,3,4,5,6,7,8,9,10]要在角的html側制作nxn矩陣。

我知道我可以先將2d in typescript file [[1,2,3,4,5],[6,7,8,9,10]]的數組划分為2d in typescript file [[1,2,3,4,5],[6,7,8,9,10]]然后使用* ngFor遍歷html中的元素。

但是我試圖找到一種方法來使用component.html中的單個數組顯示矩陣,而不將其轉換為2d數組。

輸出:

1 2 3 4 5
6 7 8 9 10

如果要在模板中顯示矩陣而在打字稿方面沒有任何邏輯,則可以使用Array.prototype.slice生成與行數相同的數組。 然后使用ngFor對該數組進行迭代,並從index變量獲取index ,這將成為您的行索引。

然后使用內部ngFor並再次slice ,以從數組和行索引中獲取行。

您只需將n設置為每行的項目數:

<div *ngFor="let row of arr.slice(0, arr.length / n % 1 === 0 ? arr.length / n : arr.length / n + 1); let idx = index">
  <span *ngFor="let x of arr.slice(idx * n, idx * n + n)">{{ x }}</span>
</div>

請參閱此stackblitz演示

但是,我認為一個更優雅的解決方案是從打字稿中的數組創建一個矩陣,然后簡單地對行和列進行迭代:

const arr = [1,2,3,4,5,6,7,8,9,10];
const n = 4;
const matrix = Array
  .from({ length: Math.ceil(this.arr.length / this.n) }, (_, i) => i)
  .map(i => this.arr.slice(i * this.n, i * this.n + this.n));
<div *ngFor="let row of matrix">
  <span *ngFor="let x of row">{{ x }}</span>
</div>

或者,您也可以使用具有一定角度的管道(該行長度為4)來創建該矩陣:

<div *ngFor="let row of arr | toMatrix:4">
  <span *ngFor="let x of row">{{ x }}</span>
</div>

然后管道將保留創建矩陣的邏輯:

@Pipe({
  name: 'toMatrix'
})
export class ToMatrixPipe implements PipeTransform {
  transform(arr: number[], n: number): number[][] {
    const rows = Array.from({ length: Math.ceil(arr.length / n) }, (_, i) => i);
    return rows.map(idx => arr.slice(idx * n, idx * n + n));
  }
}

您可以執行以下操作來實現。 我將展示兩個示例,一個示例使用2d數組,另一個示例使用單數組。

2D陣列

var a = [[1,2,3],[4,5,6]];
now to get an element placed at Xth row and Yth column you will use

a[X-1][Y-1]
e.g. to get element form 1st row and 2nd column we will print 

a[1-1][2-1] = a[0][1];

一維陣列

var a = [1,2,3,4,5,6];

now to achieve 2D like functionality first define the strength of row.
let that be L. In our case strength of row will be L = 3.

now to get an element placed at Xth row and Yth column you will use
a[Z*(X-1)+ (Y-1)]
e.g. to get element form 1st row and 2nd column we will print 

a[3*(1-1) + (2-1)] = a[1];

您可以簡單地使用%運算符。

 let nmatrix = (n) => { let temp = [] for(let i=1;i <1+(n*n); i++){ temp.push(i) if(i % n === 0) { console.log(...temp) temp = [] } } } nmatrix(4) 

暫無
暫無

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

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