如何以角度迭代数组数组

时间:2021-05-12 07:08:09

标签: javascript angular typescript

我有以下数据集,我想访问每个数据集的 x 和 y 值。我怎样才能访问 x 和 y 值?

enter image description here

3 个答案:

答案 0 :(得分:1)

解决方法很简单,你必须迭代第一个数组,这个数组的每个条目都是另一个数组,所以你也必须迭代它。

 for(const items of firstArray)  {
      for(const object of items) {
        console.log(object.x);
        console.log(object.y);
      }
    
    }

就性能而言,此解决方案比使用 forEach 的解决方案更好。 https://betterprogramming.pub/should-you-stop-using-foreach-in-your-javascript-code-efe1e86c78e5

答案 1 :(得分:0)

您可以使用任何迭代器来遍历数组。

array.forEach(item => 
           item.forEach(
             sub => console.log(sub.x,sub.y)
           ));

答案 2 :(得分:0)

您可以使用嵌套的 ngFor 循环访问 angular 中嵌套数组的值。可以这样实现。

 <div *ngFor="let item of Array1;let i = index" >                         
     <div *ngFor="let subItem of item[i]"> 
          <p>{{subItem.x}}</p> 
          <p>{{subItem.y}}</p> 
     </div>                             
 </div>