簡體   English   中英

數組中有值,但無法訪問它們,這可能是什么問題?

[英]Array has values in it, but not able to access them, what might be the problem?

我通過一個回調函數得到兩個值(字符串),假設這兩個值是a和b,所以現在我將這些值壓入數組。 當我console.log這個數組時,只有當我通過單擊箭頭符號擴展數組時,它才會顯示這些值。 當我嘗試訪問索引值時,它說未定義。 所以我猜有一個問題函數調用嗎?

funcOuter() {
    let newList =[];
    this.calledFunc(function (param) {
        newList.push(param);
    });
    console.log(newList[1]);
}

實際輸出:

未定義

預期產量:

123.234.556

如果您使用angular 2+,為什么要具有回調功能,我認為這是一個解決方案。

export class AchievementComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  async funcOuter() {
    let newList =[];
    const param = await this.funcInner();
    newList.push(param);
  }

  funInner() {
    return new Promise((resolve, reject)=>{
      this.calledFunc((param)=>{
         resolve(param);
      })
    })
  }

}

最好是可視化代碼執行:

堆棧S

H

隊列Q

執行時,將funcOuter放在S上

與分配,函數調用和日志一樣:

SfuncOuterlet newList =[];

分配已執行...

SfuncOuterthis.calledFunc(callback);

函數被執行...

SfuncOuterthis.calledFunc(callback); calledFunc inner block

內部塊和異步完成

SfuncOuterconsole.log(newList[1])

possible async calls

日志完成:

SfuncOuter

possible async calls

外部完成:

S

possible async calls

從Q填充堆棧:

Scallback

possibly more async calls

推送被執行:

Scallbackpush

等等;) 事件循環

因此,將您的代碼更改為:

funcOuter() {
    let newList =[];
    this.calledFunc(function (param) {
        newList.push(param);
        newList[1] && console.log(newList[1]);
    });

}

應該給出預期的結果。

暫無
暫無

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

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