简体   繁体   English

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

[英]global Array.length has value inside function but is 0 outside function but still has same objects

I have created a function to loop through a weeks worth of employee shifts to pull out only today's shifts. 我创建了一个功能,可以循环进行数周的员工轮班,以仅退出今天的轮班。 The function as expected. 该功能符合预期。 When I output the todayAr in console at the end of the function, I get: 在函数末尾在控制台中输出todayAr时,我得到:

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

-- the array of objects with an accurate array length. -具有精确数组长度的对象数组。

But when I reference that same variable with console in a 'document.ready(function()' block, I get: 但是,当我在'document.ready(function()')块中使用控制台引用同一变量时,我得到:

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

I can't loop through the array because the length is 0 and any reference using [0], [1] etc returns undefined. 我无法遍历数组,因为长度为0,并且任何使用[0],[1]等的引用都返回未定义。 This has been driving me crazy for about 8 hours...I have tried every variation for building the object and always seem to get the same result which means I am probably missing something stupid and obvious but just can't see it. 这使我发疯了大约8个小时...我尝试了构建对象的各种变体,并且似乎总是得到相同的结果,这意味着我可能缺少一些愚蠢而明显的东西,但看不到它。

Here is the call: 这里是电话:

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

Here is the function: 这是函数:

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

Here is the addSchedule function: 这是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; 
}

The fetchJSONFile call is an asynchronous call meaning it initiates the process but returns the results at some later time. fetchJSONFile调用是一个异步调用,这意味着它会启动该过程,但稍后会返回结果。 This means that a is still empty when you return from the function. 这意味着从函数return时, a仍然为空。 That is what you are seeing - length is 0 because at that time it is still an empty array. 那就是您所看到的-length为0,因为那时它仍然是一个空数组。

Some time later, the results are available, so fetchJSONFile calls the provided function (the second parameter in your function call), providing it the data. 一段时间后,结果可用,因此fetchJSONFile调用提供的函数(函数调用中的第二个参数),向其提供数据。 At that point you have the data but not prior. 届时您将拥有数据,但没有数据。

To get the data in your document.ready logic you will need to do something like this: 要在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);
  });
} 

This uses a "callback" function, a common approach to handling situations where getting data is not immediate. 这使用“回调”功能,这是处理不立即获取数据的情况的常用方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 array.length和空函数没有帮助我 - array.length and empty function is not helping me 用javascript array.length函数产生奇怪的结果 - Strange results with javascript array.length function React array.length 返回 0 即使数组有项目 - React array.length returning 0 even though array has items 为什么该变量在 function 内部工作,但当它放在 function 外部时却没有工作,尽管它具有全局 scope? - why the variable is working inside the function but not when it is placed outside the function though it has global scope? 变量在函数内部和外部具有不同的值 - Variable has different values inside and outside a function JavaScript Array.length属性是函数还是简单变量? - Is the JavaScript Array.length property a function or a simple variable? JavaScript - Object 属性作为 function 结果,如 Array.length - JavaScript - Object property as a function result like Array.length 当将 array.length 传递给 reactjs 中的 function 时,它给出了 undefined - when passing array.length to a function in reactjs it gives undefined 将数组中具有相同值的对象排序到同一数组中的一个 object - sort the objects in array that has same value to one object inside the same array 如何编写一个 function,它创建一个特定长度的对象数组? Object 有自定义生成数据 - How to write a function, which creates an array of objects of certain length? Object has custom generated data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM