[英]JSON variable undefined when global
我想全局設置一個變量“ 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');
}
但是,當我嘗試在其他函數中使用變量城市時 ,卻得到了未定義的數據:
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 + '°C' + '<br>' + ' Low: ' + low + '°C' + '</p>');
});
});
請幫忙。
而不是做
var city = data.current_observation.display_location.full;
你應該做
city = data.current_observation.display_location.full;
為了設置全球city
變量的值。 重用var
關鍵字將在函數范圍內而不是全局范圍內聲明一個新的變量city
。
有點晚了,但這是一個例子。 (@ 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
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
在funtion conditions
刪除var city
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.