簡體   English   中英

如何在 Typescript 中推送數組中的元素

[英]How to push elements in an Array of Array in Typescript

我是 typescript 的新手。 我在 Angular 中創建了一個Monthpicker小部件。 最初,它非常復雜並且有很多功能。 所以,我會盡量保持簡單。 這是我的代碼。

monthpicker.component.ts

import { Component } from '@angular/core';

@Component({
  ...
})
export class AppComponent  {

  monthsViewSlices: Array<Array<number>>;

  ngOnInit(): void {
    this.monthsViewSlices = [[0, 24], [6, 30], [18, 42], [30, 54], [42, 66], [54, 78]];
    console.log(this.monthsViewSlices);
  }
}

而這些monthViewSlices實際上是這樣的切片:

在此處輸入圖像描述

月份索引從 0 開始。如您所見,我對切片進行了硬編碼,如下所示:

this.monthsViewSlices = [[0, 24], [6, 30], [18, 42], [30, 54], [42, 66], [54, 78]];

這不是一件好事。 我想使用for循環使其可配置。 我試過這段代碼:

  ngOnInit(): void {
    const lowerBound=2012;
    const upperBound=2015;
    let x;
    let y;
    let z;
    let iterations=upperBound-lowerBound;
    for(x=lowerBound; x<=upperBound; x++) {
      for(y=0; y<=24; y++) {
        //DO NOTHING JUST ITERATE
      }
      this.monthsViewSlices.push([0,y]);
    }
    console.log(this.monthsViewSlices);
  }

但我不知道如何處理Array<Array<number>> 我還嘗試從這些方面尋求幫助:

  1. “push()” 到 Typescript 中的數組
  2. 如何在數組數組中推送 object
  3. typescript 以循環方式將元素推入數組
  4. TypeScript 中的 Arrays 數組

簡單的push()方法在這里不起作用。 我試過了。 或者可能沒有以正確的方式。 所以,我在這里做了很多體操。

但我無法使這個動態而不是硬編碼。

應注意以下事項:

  1. 切片數等於iterations ,即upperBound-lowerBound
  2. 第一個和第二個切片之間的差異是 6,而對於 rest,它是 12: 在此處輸入圖像描述

我也創建了一個堆棧閃電戰 請有人幫我實現這一目標。 讓我知道這個問題是否需要更多細節。 並告訴我這是否可行,或者我在浪費我和每個人的時間。

如果我正確閱讀了您的示例,則您需要 3 個“切片”(在這種情況下是 2012 年和 2015 年之間的差異),從而導致

[0, 24]
[6, 30]
[18, 42]

我在這里分叉了你的堆棧閃電戰

您操作數組的方式並沒有錯(我個人更喜歡將數組鍵入為 [] 而不是 Array<>,但這只是個人喜好),循環邏輯只需要一點幫助。

編輯:來自stackblitz fork的代碼:

  years: number[] = [];
  monthsViewSlices: number[][] = [];

  ngOnInit(): void {
    const lowerBound=2012;
    const upperBound=2015;

    let x = 0;
    let y = 24;
    let iterations=upperBound-lowerBound;
    for(let i=0; i<iterations; i++) {      
      this.monthsViewSlices.push([x, y]);
      const increment = i === 0 ? 6 : 12;
      x+=increment;
      y+=increment;

    }
    this.monthsViewSlices.forEach(slice => console.log(slice));
  }

首先,像這樣創建一個空數組let month: string[] = []; ,你可以使用 const 或 let,如果你在 function 內部聲明使用 let,否則使用 const 或 var,這完全取決於你。

你有一個數組this.monthsViewSlices = [[0, 24], [6, 30], [18, 42], [30, 54], [42, 66], [54, 78]]; 如果您希望特定元素推入新數組,您可以使用類似的東西。

    for(let month in monthsViewSlices){ 
       if monthsViewSlices[month].includes(value/condition) === true){
          month.push(monthsViewSlices[month])
          } 
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM