
如上圖,我兩種都使用typeof查詢,兩個都是物件。
但是我第二個陣列我無法取得length,也無法使用比方說像array[0]這樣的方式console出來,請問問題出在哪?
附上程式碼
    var report_log = []
    fetch(link)
    .then(function(response) {
        return response.json();
    })
    .then(function(myJson) {
        // console.log(myJson);
        for(k=0; k<myJson.length; k++){
            if(myJson[k].project_name == projectname){
                report_log.push(myJson[k])
            }
        }
    });
    console.log(report_log)
                        就像 Leo 大說的那樣,因為 fetch 是非同步操作,所以需要稍微修改你的程式碼,確保邏輯正確:
    var report_log = []
    fetch(link)
    .then(function(response) {
        return response.json();
    })
    .then(function(myJson) {
        // console.log(myJson);
        for(k=0; k<myJson.length; k++){
            if(myJson[k].project_name == projectname){
                report_log.push(myJson[k])
            }
        }
    });
    .finally(()=>{
        console.log(report_log)
    })
至於根本原因,是因為 fetch() 在 JS 的 Event loop 中從 Stack 被 Pop 出去以後會交由 WebAPI (瀏覽器)處理,等到處理完畢再將它放到 Queue 中。此時, console.log(report_log) 早就已經被處理完成了,因此,看不到任何東西是很正常的。