使用单个数组显示矩阵 angular component.html

Show a matrix using a single array angular component.html

我有一个数组假设 [1,2,3,4,5,6,7,8,9,10] 想在 angular 的 html 侧创建 nxn 矩阵。

我知道我可以先将数组划分为 2d in typescript file [[1,2,3,4,5],[6,7,8,9,10]] 并使用 *ngFor 遍历 html 中的元素。

但我正在尝试找到一种方法来在 component.html 中使用单个数组显示矩阵,而不将其转换为二维数组。

输出:

1 2 3 4 5
6 7 8 9 10

您可以通过以下方式实现。 我将展示这两个示例,一个是二维数组,另一个是单个。

二维数组

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)

如果你想在模板中显示矩阵而不需要打字稿端的任何逻辑,你可以使用 Array.prototype.slice 生成一个与你的行数一样长的数组。然后使用 ngFor 迭代该数组并从 index 变量中获取索引,这将是您的行索引。

然后再次使用内部 ngForslice 从数组中获取行和行索引。

您只需将 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>

See this stackblitz demo.

但是,我认为一个更优雅的解决方案是在 typescript 中从数组创建一个矩阵,然后简单地迭代行和列:

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>

或者您可以使用 angular 中的管道创建该矩阵,类似这样,行长度为 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));
  }
}