簡體   English   中英

在角度循環遍歷數組時無法讀取未定義的0屬性

[英]cannot read property of 0 undefined while looping through array in angular

我試圖遍歷項目數組並推送到另一個數組,但項目列表中的索引為“ 0”,但仍然能夠獲得所提及的錯誤。 請找到下面的代碼

  createReportFormulaInfo(): Array<ReportFormulaEntity> {
    debugger;
    for (let sta in this.selectedSources) {
      debugger;
      let ido = this.selectedSource[sta].id;
      this.selectedFormulaList.push({
        Market_OV: this.selectedSources[sta].Market,
        Set_Name: this.selectedSources[sta].Value,
        Data_ID: Number(this.selectedSources[sta].Market),
        Set_number: 0,
        Formula_Set1: "",
        Formula_Set2: "",
        Formula_type: "",
        Date_From: "",
        Date_To: "",
        UpdateFlag: "A",
        Is_Current: 0
      });
    }
   }

我不確定如何解決此問題,並且我使用的是角度4。有人可以在此查詢中提供幫助嗎? 提前謝謝了。

來自https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in

注意:for ... in不應用於遍歷索引順序很重要的Array。

您將基於局部變量進行迭代

 createReportFormulaInfo(): Array<ReportFormulaEntity> {
    debugger;
    for (i=0;i<this.selectedSources.length;i++) {
      debugger;
      let ido = this.selectedSource[i].id;
      this.selectedFormulaList.push({
        Market_OV: this.selectedSources[i].Market,
        Set_Name: this.selectedSources[i].Value,
        Data_ID: Number(this.selectedSources[i].Market),
        Set_number: 0,
        Formula_Set1: "",
        Formula_Set2: "",
        Formula_type: "",
        Date_From: "",
        Date_To: "",
        UpdateFlag: "A",
        Is_Current: 0
      });
    }
   }

另一種方法是使用數組的foreach方法

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

暫無
暫無

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

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