代码之家  ›  专栏  ›  技术社区  ›  da_funk

全局时未定义JSON变量

  •  0
  • da_funk  · 技术社区  · 8 年前

    城市 “global并在其他函数中使用它。我正在请求一个JSON数据,它似乎在这个函数中工作

    var city;
    
    function conditions(data) {
            var city = data.current_observation.display_location.full;
            var wcode = data.current_observation.icon;
    
            $('#city').append('<h2>' +'Weather forecast in ' + city + '</h2>');
            $('#city').addClass('headings-style');
    
        }
    

    城市 在另一个函数中,我得到一个未定义的数据:

    function forecastDays(info) {
            var locationOne = info.forecast.simpleforecast.forecastday;
            locationOne.forEach(function (daysPlus) {
    
            var high = daysPlus.high.celsius;
            var low = daysPlus.low.celsius;
            var arr = ["day1", "day2", "day3", "day4"];
            jQuery.each(arr, function (i, val) {
    
                $("#temp_" + val).html('<p>' + city + 'High: ' + high + '&deg;C' + '<br>' + ' Low: ' + low + '&deg;C' + '</p>');
    
                });
            });
    

    请帮忙。

    3 回复  |  直到 8 年前
        1
  •  4
  •   J. Chen    8 年前

    而不是做

    var city = data.current_observation.display_location.full;
    

    city = data.current_observation.display_location.full;
    

    为了设置全局 city var 关键字将声明一个新变量 城市 在功能范围内,而不是全局。

        2
  •  1
  •   wahwahwah    8 年前

    有点晚了,但这里有一个例子。 (@J.陈提供了答案)

    当您使用 var city = 您正在函数范围内重新定义变量,因此它不再可以从全局范围访问。

    在下面的示例中 city 变量在全局范围内正确使用,其中 town 正在函数范围中重新定义变量:

    var city;
    var town;
    
    function foo() {
      city = "New York";
      var town = "Boston";
    };
    
    function bar() {
      console.log(city);
      console.log(town);
    }
    
    foo(); // assigns the variable a value
    bar(); // console "New York" / undefined
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        3
  •  -1
  •   Junior Abreu    8 年前

    删除var city 在里面 funtion conditions