【问题标题】:JSON variable undefined when global全局时 JSON 变量未定义
【发布时间】:2017-07-20 19:52:28
【问题描述】:

我想将变量“city”设为全局变量并在其他函数中使用它。我正在请求一个 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');

    }

但是当我尝试在其他函数中使用变量 city 时,我得到了一个未定义的数据:

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>');

            });
        });

请帮忙。

【问题讨论】:

  • 您在conditions 内重新声明city。使用city = ... 而不是var city = ...
  • 一个好问题!这是一个经常犯的错误,因此最好注意这一点。

标签: javascript jquery json variables global


【解决方案1】:

而不是做

var city = data.current_observation.display_location.full;

你应该这样做

city = data.current_observation.display_location.full;

为了设置全局city变量的值。重复使用 var 关键字将在函数范围内声明一个新变量 city,而不是全局。

【讨论】:

    【解决方案2】:

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

    当您使用 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
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案3】:

      删除funtion conditions中的变量city

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-08
        • 2018-09-17
        • 1970-01-01
        • 1970-01-01
        • 2019-10-01
        • 1970-01-01
        • 2014-02-02
        相关资源
        最近更新 更多