gpt4 book ai didi

javascript - 为什么javascript代码的输出不稳定

转载 作者:行者123 更新时间:2023-12-02 17:58:31 24 4
gpt4 key购买 nike

我编写了以下代码。

var arrCityrecordForADay = [];
function getWeatherDataForCities(cityArray, callback) {

var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24 * 60 * 60);
for (var i in cityArray) {

for (var j = 1; j <= 2; j++) {
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q=" + cityArray[i] + "&dt=" + toDaysTimestamp;

$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
var arrCityRecordForDay = [];
arrCityRecordForDay.push({
"cityName": data.list[0].city.name
}, {
"weather": data.list[0].weather[0].description
});

var tempId = data.list[0].city.name+""+timeConverter(data.list[0].dt);
arrCityrecordForADay.push({
tempId: arrCityRecordForDay // Here tempId is inserted as "tempId" not its value
});

if (((arrCityrecordForADay.length)) === cityArray.length) {
callback(arrCityrecordForADay);
}

}
});
toDaysTimestamp = toDaysTimestamp - (24 * 60 * 60);
}
}
}

$(document).ready(function () {
var cityArray = new Array();
cityArray[0] = "pune";
cityArray[1] = "london";
var result = document.getElementById("msg");
getWeatherDataForCities(cityArray, function (jsonData) {
var myJsonString = JSON.stringify(jsonData);
console.log(myJsonString);
});
});

function timeConverter(UNIX_timestamp){

var a = new Date(UNIX_timestamp*1000);

var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

var year = a.getFullYear();

var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
//var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
var time = date+''+month+''+year;
return time;
}

程序的输出不稳定。我的意思是2-3刷新后有时显示正确的输出,有时显示错误。

正确的输出是

"[{"Pune25Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]},{"London22Dec2013":[{"cityName":"London"},{"weather":"overcast clouds"}]}]"

输出错误

"[{"Pune25Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]},{"Pune24Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]}]"

代码工作流程出了什么问题。谢谢

Fiddle

您的回复将受到赞赏!

最佳答案

解决您的问题的一些事情:

  1. 在成功回调中,如果您创建哈希变量,它将允许您将 tempId 设置为对象的键。 (就像现在一样,您的代码示例甚至与您显示的输出不匹配)。

    var arrCityRecordForDay = [];
    arrCityRecordForDay.push({
    "cityName": data.list[0].city.name
    }, {
    "weather": data.list[0].weather[0].description
    });

    var tempId = data.list[0].city.name+""+timeConverter(data.list[0].dt);
    // updated code
    var hash = {};
    hash[tempId] = arrCityRecordForDay;

    arrCityrecordForADay.push(hash);
  2. 当 arrCityrecordForADay 长度与 cityArray 相同时,会发生回调,但由于您正在使用每个城市的多个时间戳进行内部循环,因此该检查应该不同。

    // update length check (the 2 here should be however much inner loop is)
    if (((arrCityrecordForADay.length)) === cityArray.length * 2) {
    callback(arrCityrecordForADay);
    }
  3. 我确认“London”的 JSON 响应会在页面刷新时首先定期返回。您正在发出多个 JSON 请求,它们可以按任何顺序返回。因此,您的 arrCityrecordForADay 数组可以首先包含伦敦或浦那(以及任一城市的任一日期),具体取决于请求的速度。为了使其具有确定性,您可以按字母顺序排序。或者只是存储为对象(哈希)而不是数组。解决上述问题 2 后,此项目将更有意义。

要排序,一种方法是使用数组的数组,而不是哈希数组..(更简单的模型,因为每个哈希都只有一个元素),然后定义排序方法。

var tempId = data.list[0].city.name+""+timeConverter(data.list[0].dt);
// array instead of hash
arrCityrecordForADay.push([tempId, arrCityRecordForDay]);

if (((arrCityrecordForADay.length)) === cityArray.length * 2) {
callback(arrCityrecordForADay.sort(compareCities));
}

...

// define this on page somewhere - looks at first element in array (the "tempId" value from above)
function compareCities(a,b) {
if (a[0] < b[0])
return -1;
if (a[0] > b[0])
return 1;
return 0;
}

关于javascript - 为什么javascript代码的输出不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20780771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com