简体   繁体   English

外部功能范围可变

[英]Variable outside function scope

I have function that reads json document, dayNames and monthNames are visible outside function, but date format isn't. 我有读取json文档的函数,在函数外部可见dayNames和monthNames,但日期格式却不可见。 Inside function it correctly prints its value but outside it doesn't update outside value. 内部函数可以正确打印其值,但外部函数不会更新外部值。 So why dateFormat doesn't update outside function? 那么为什么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: 

The problem is $.getJSON() is an asynchronous call. 问题是$.getJSON()是异步调用。 The console.log(dateFomrat) outside the function runs before the function finishes. 函数外部的console.log(dateFomrat)在函数完成之前运行。 The code continues while the $.getJSON() is running so dateFormat isn't set when the second(outside) console.log() executes. 代码在$.getJSON()运行时继续执行,因此在第二(外部) console.log()执行时未设置dateFormat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM