我有一个数组假设[1,2,3,4,5,6,7,8,9,10]希望在角度的html侧制作nxn矩阵。
我知道我可以先将数组划分为打字稿文件1,2,3,4,5],[6,7,8,9,10中的2d并迭代…
如果要在模板中显示矩阵而在打字稿一侧没有任何逻辑,则可以使用 Array.prototype.slice 只要你的行数生成一个数组。然后使用。迭代该数组 ngFor 并从中获取索引 index 变量,这将是你的行索引。
ngFor
index
然后用内心 ngFor 和 slice 再次从您的数组和行索引获取行。
slice
你只需要设置 n 到每行的项目数:
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演示 。
但是,我认为更优雅的解决方案是在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>
或者您可以使用角度管道创建该矩阵,类似于此,行长度为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)); } }
你可以简单地使用 % 运营商。
%
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)
你可以通过以下方式实现它。 我将展示两个示例,一个是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];
1D阵列
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];