簡體   English   中英

外部功能范圍可變

[英]Variable outside function scope

我有讀取json文檔的函數,在函數外部可見dayNames和monthNames,但日期格式卻不可見。 內部函數可以正確打印其值,但外部函數不會更新外部值。 那么為什么dateFormat不會更新外部函數?

var dayNames = [];
var monthNames = [];
var dateFormat = "";
$.getJSON("/Scripts/cldr/main/"+ culture + "/ca-gregorian.json", function (json) {
    $.each(json.main.@(System.Threading.Thread.CurrentThread.CurrentCulture.Name).dates.calendars.gregorian.days.format.short, function (key, val) {
        dayNames.push(val);
    });
    $.each(json.main.@(System.Threading.Thread.CurrentThread.CurrentCulture.Name).dates.calendars.gregorian.months["stand-alone"].wide, function (key, val) {
        monthNames.push(val);
    });
    dateFormat = json.main.@(System.Threading.Thread.CurrentThread.CurrentCulture.Name).dates.calendars.gregorian.dateFormats.medium;
    console.log(dateFormat);  //Output: y-MM-dd
});
console.log(dateFormat); //Output: 

問題是$.getJSON()是異步調用。 函數外部的console.log(dateFomrat)在函數完成之前運行。 代碼在$.getJSON()運行時繼續執行,因此在第二(外部) console.log()執行時未設置dateFormat

暫無
暫無

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

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