首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用单个阵列角component.html显示矩阵

使用单个阵列角component.html显示矩阵
EN

Stack Overflow用户
提问于 2019-03-17 09:10:20
回答 3查看 5.4K关注 0票数 4

我有一个数组,假设[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数组。

产出:

代码语言:javascript
复制
1 2 3 4 5
6 7 8 9 10
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-17 09:52:38

如果您希望在模板中显示矩阵,而不需要在类型记录端显示任何逻辑,则可以使用Array.prototype.slice生成一个数组,只要您的行数即可。然后使用ngFor在该数组上迭代,并从index变量中获取索引,这将是您的行索引。

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

您只需将n设置为每行的项数:

代码语言:javascript
复制
<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演示

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

代码语言:javascript
复制
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));
代码语言:javascript
复制
<div *ngFor="let row of matrix">
  <span *ngFor="let x of row">{{ x }}</span>
</div>

或者,您可以使用一个角度的管道创建矩阵,类似于这样,行长为4:

代码语言:javascript
复制
<div *ngFor="let row of arr | toMatrix:4">
  <span *ngFor="let x of row">{{ x }}</span>
</div>

然后,管道将保存创建矩阵的逻辑:

代码语言:javascript
复制
@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));
  }
}
票数 4
EN

Stack Overflow用户

发布于 2019-03-17 09:27:11

你可以做下面的事情来实现它。我将展示这两个例子,一个是2d数组,另一个是单列。

二维阵列

代码语言:javascript
复制
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];

一维阵列

代码语言:javascript
复制
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];
票数 2
EN

Stack Overflow用户

发布于 2019-03-17 09:29:52

您可以简单地使用%操作符。

代码语言:javascript
复制
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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55205493

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档