global Array.length在函数内部具有值,但在函数外部为0但仍具有相同的对象

时间:2017-03-11 02:54:56

标签: javascript jquery arrays json

我已经创建了一个功能,可以通过几周的员工轮班来解决今天的轮班问题。功能如预期。当我在函数结束时在控制台中输出todayAr时,我得到:

Array[4]    // 4 here...all is good
 >0:Object
 >1:Object
 >2:Object
 >3:Object
 length:4

- 具有精确数组长度的对象数组。

但是当我在&document文件中使用控制台引用相同的变量时,我得到了:

Array[0]   // notice the 0...can't loop or reference the objects
 >0:Object
 >1:Object
 >2:Object
 >3:Object
 length:4

我无法遍历数组,因为长度为0,任何使用[0],[1]等的引用都会返回undefined。 这让我疯狂了大约8个小时...我已经尝试了每个变体来构建对象并且似乎总是得到相同的结果,这意味着我可能错过了一些愚蠢而明显但却无法看到的东西。

这是电话:

$(document).ready(function() {          
    var todayAr = [];
    getTodayShifts(todayAr);
    console.log(todayAr);   // length here is 0 but the array elements are there        
});

这是功能:

function getTodayShifts(a) {
    var d = new Date(); 
    var thisDay = getSpan( d, 'd');
    var i = 0;  
    fetchJSONFile('data/dataSch.cfm', function(data){                                               
        var StartDate;
        $.each(data, function(key, val) {                           
            StartDate = getSpan( val.StartDate, 'd');                                                           
            if (thisDay == StartDate)  { 
                a[i] = addSchedule(val.SID, val.empID, val.StartDate, val.EndDate, val.deptId, val.idn, val.secID);                         
                i++;                                    
            }                                           
        });                 
        console.log(a); // everything is fine here
    });
    return;
} 

这是addSchedule函数:

function addSchedule(SID, empID, StartDate, EndDate, deptId, idn, secID ) {
    var item = {"SID":  SID,
        "empID":  empID,
        "StartDate":  StartDate,
        "EndDate":  EndDate,
        "deptId":  deptId,
        "idn":  idn,
        "secID":  secID};   
    return item; 
}

1 个答案:

答案 0 :(得分:0)

fetchJSONFile调用是异步调用,意味着它启动进程但稍后返回结果。这意味着当您从函数areturn仍为空。这就是你所看到的 - 长度是0,因为那时它仍然是一个空数组。

一段时间后,结果可用,因此fetchJSONFile调用提供的函数(函数调用中的第二个参数),为其提供数据。那时你有数据但不是先前的数据。

要获取document.ready逻辑中的数据,您需要执行以下操作:

$(document).ready(function() {
  getTodayShifts(function(data) {
    console.log(data);
  });
});

function getTodayShifts(cb) {
  var a = [];
  var d = new Date();
  var thisDay = getSpan( d, 'd');
  var i = 0;
  fetchJSONFile('data/dataSch.cfm', function(data){
    var StartDate;
    $.each(data, function(key, val) {
      StartDate = getSpan( val.StartDate, 'd');
      if (thisDay == StartDate)  {
        a[i] = addSchedule(val.SID, val.empID, val.StartDate, val.EndDate, val.deptId, val.idn, val.secID);
        i++;
      }
    });
    console.log(a); // everything is fine here
    cb(a);
  });
} 

这使用"回调"函数,一种处理不立即获取数据的情况的常用方法。