[英]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>>
。 我還嘗試從這些方面尋求幫助:
簡單的push()
方法在這里不起作用。 我試過了。 或者可能沒有以正確的方式。 所以,我在這里做了很多體操。
但我無法使這個動態而不是硬編碼。
應注意以下事項:
我也創建了一個堆棧閃電戰。 請有人幫我實現這一目標。 讓我知道這個問題是否需要更多細節。 並告訴我這是否可行,或者我在浪費我和每個人的時間。
如果我正確閱讀了您的示例,則您需要 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.