【问题标题】:Split a 2d array typescript html with slice用切片拆分二维数组打字稿html
【发布时间】:2021-05-03 14:05:18
【问题描述】:

我正在尝试使用slice 在我的页面视图中拆分矩阵的列。如果我slice:0:1,页面只显示第一列。但我不明白为什么如果我尝试选择 slice:1:2 它不会只显示第二列,但仍然只显示第一列。 2:33:4 等也一样。

<div class="container">    
    <tr *ngFor="let row of matrix; index as r">
        <td *ngFor="let column of row|slice:0:1; index as c">
            
            <select [(ngModel)]="object[r][c]">
            {{r}}{{c}}
            </select>
        
        </td>
    </tr>
</div>
ngOnInit() {
    for (let r = 0; r < 6; r++) {
      this.normalizedMatrix.push([0, 0, 0, 0, 0, 0])
      this.matrix[r] = []
      this.object[r] = {}
      this.object[r][r] = 1
      for (let c = 0; c < 6; c++) {
        if (r == c) {
          this.matrix[r].push(1)
          this.object[r][c] = 1
        }
        if (r > c) {
          this.matrix[r].push(1 / 9)
          this.object[r][c] = 1 / 9
        }
        else if (r < c) {
          this.matrix[r].push(9)
          this.object[r][c] = 9
        }
      }
    }
    this.onSelectChange(0, 0)
  }

【问题讨论】:

  • 切片返回什么?听起来它可能会返回已删除的列?你能给我们看一个matrix值的例子吗?
  • @joshvito 我使用 slice 不是删除列,而是因为我想要矩阵值的列表视图。这似乎是最好的解决方案。您认为有更好的方法来查看列出的矩阵的 html 吗?
  • 这可能有效,您是否尝试过从column 变量中渲染出一个值?当slice 管道的值发生变化时,索引c 可能会发生变化。

标签: html typescript matrix multidimensional-array slice


【解决方案1】:

Here is a working example of the pipe. 似乎您只是在查看列索引值,它会随着管道值而变化。这是因为切片管道的作用类似于 js 切片,因为它“创建一个包含元素子集(切片)的新数组或字符串”。 ng docs

//component.html
<div class="container">
    <tr *ngFor="let row of matrix; index as r">
        <td *ngFor="let column of row|slice:1:2; index as c">

            <p>R: {{r}} C: {{c}} - {{column}}</p>>

        </td>
    </tr>
</div>


//component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  matrix = [
    ['row 1 col 1', 'row 1 col 2'],
    ['row 2 col 1', 'row 2 col 2'],
    ['row 3 col 1', 'row 3 col 2']
  ];
}

【讨论】:

  • 啊好的,我明白了。但现在我有一个问题。我需要变量 c 从 .ts 预插入数据。我不能用列替换它。我在主要问题中添加了 .ts
  • 我不会以依赖视图索引的方式编写组件,因为它不可靠。如您所见。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 2018-12-25
  • 2017-11-16
  • 1970-01-01
  • 2018-05-06
相关资源
最近更新 更多