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

时间:2013-12-26 07:15:10

标签: javascript json

我写了以下代码。

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 个答案:

答案 0 :(得分:2)

要解决问题的一些事项:

  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. 我确认“伦敦”的JSON响应会在页面刷新时定期返回。您正在解雇多个JSON请求,他们可以按任何顺序返回。因此,根据请求的速度,您的arrCityrecordForADay数组可以包含伦敦优先或Pune(以及任一城市的任一日期)。为了使其具有确定性,您可以按字母顺序排序。或者只是存储为对象(哈希)而不是数组。一旦您修复上述问题2,此项目将更有意义。

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

    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;
    }