价值未评估

时间:2019-05-02 19:25:02

标签: javascript jquery

我有一个不寻常的问题,我无法确定为什么会发生。我创建了一个对象,并从循环中更新了值。此循环完成后,我尝试访问一个未定义的值。我认为这可以通过向我展示代码来最好地证明。谁能帮助我了解这里发生的事情?

function loadCounts() {

    var counts = {
        enroll: {},
        term: {},
        change: {}
    };

    var forms = [
        "enroll/pending",
        "enroll/approved",
        "term/pending",
        "term/approved",
        "change/pending",
        "change/approved",
    ];

    $.each(forms, function( index, value ) {

        if (!(value.split("/")[0] in counts)) {
            counts[value.split("/")[0]] = {};
        }

        $.ajax({
            url: apiURL+'/online/payroll/admin/dashboard/counts/'+value,
            headers: { 'Authorization': 'Bearer ' + sessionStorage.getItem('apiToken') },
            crossDomain: true,
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                counts[value.split("/")[0]][value.split("/")[1]] = response.count;
            },
            error: function (XMLHttpRequest) {
                console.log("error", XMLHttpRequest)
            }
        });
    });

    console.log('count object:', counts)
    console.log('enroll object:', counts.enroll)
    console.log('pending count:', counts.enroll.pending)
}

loadCounts();

然后在控制台中显示结果:

enter image description here

1 个答案:

答案 0 :(得分:-1)

您的代码正在执行异步操作,因此打印调用可能会在ajax请求返回之前进行评估。

我可以建议观看此演讲,以直观了解此处发生的事情:

https://www.youtube.com/watch?v=8aGhZQkoFbQ

另请参阅:Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference