[英]Can't able to get the minimum value from the temperature array. What might be the problem?
[英]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上
與分配,函數調用和日志一樣:
S : funcOuter
, let newList =[];
分配已執行...
S : funcOuter
, this.calledFunc(callback);
函數被執行...
S : funcOuter
, this.calledFunc(callback);
, calledFunc inner block
內部塊和異步完成
S : funcOuter
, console.log(newList[1])
,
問 : possible async calls
日志完成:
S : funcOuter
,
問 : possible async calls
外部完成:
S :
問 : possible async calls
從Q填充堆棧:
S : callback
,
問 : possibly more async calls
推送被執行:
S : callback
, push
等等;) 事件循環
因此,將您的代碼更改為:
funcOuter() {
let newList =[];
this.calledFunc(function (param) {
newList.push(param);
newList[1] && console.log(newList[1]);
});
}
應該給出預期的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.