我有一个数组,假设[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]],然后使用*ngFor迭代html中的元素。
但是,我试图找到一种方法,在component.html中使用单个数组来显示矩阵,而不将其转换为2d数组。
产出:
1 2 3 4 5
6 7 8 9 10发布于 2019-03-17 09:52:38
如果您希望在模板中显示矩阵,而不需要在类型记录端显示任何逻辑,则可以使用Array.prototype.slice生成一个数组,只要您的行数即可。然后使用ngFor在该数组上迭代,并从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));
}
}发布于 2019-03-17 09:27:11
你可以做下面的事情来实现它。我将展示这两个例子,一个是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];发布于 2019-03-17 09:29:52
您可以简单地使用%操作符。
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)
https://stackoverflow.com/questions/55205493
复制相似问题