简体   繁体   English

在 JavaScript 中使用 array.push() 后数组长度不正确

[英]incorrect array length after using array.push() in JavaScript

Fellow noob in JavaScript so forgive me if I'm missing something basic. JavaScript 菜鸟,如果我遗漏了一些基本的东西,请原谅我。

I have an array that I want to push data retrieved from an AJAX request using JQuery, where CalendarEvent is a custom class I created.我有一个数组,我想使用 JQuery 推送从 AJAX 请求中检索到的数据,其中 CalendarEvent 是我创建的自定义类。

let events=[];
$.post(url, data, function(data) {
  data.forEach(x => function(x) {
    let event = new CalendarEvent();
    events.push(event);
  });
}, "json");

My question is when I try to console.log(events) inside the function(data) method, it shows up as the correct amount of objects.我的问题是当我尝试在function(data)方法中使用console.log(events) ,它显示为正确数量的对象。 When I console.log(events) outside of the method (nothing else added or subtracted), the length is 0 and all my objects are inside an empty array.当我在方法之外console.log(events) (没有添加或减去任何其他内容),长度为 0 并且我的所有对象都在一个空数组内。 The first 2 lines in screenshot are console.log(events) outside the method, the second 2 lines are inside the method (I also don't know why they aren't showing in order).屏幕截图中的前两行是方法外的console.log(events) ,后两行在方法内(我也不知道为什么它们没有按顺序显示)。 Can anyone help me fix my problem?谁能帮我解决我的问题?

Console.log Console.log arrays expanded Console.log Console.log 阵列已扩展

In javascript all methods regular methods are called BEFORE any async code so what is happening is that your console log outside the code is happening BEFORE the method is ran, run any code that depends on the information in the ajax call inside of the method OR you can wrap any functions you need ran after that by using setTimeout().在 javascript 中,所有方法的常规方法都在任何异步代码之前被调用,所以发生的事情是代码外的控制台日志发生在方法运行之前,运行任何依赖于方法内部 ajax 调用中的信息的代码,或者你可以使用 setTimeout() 包装您需要在此之后运行的任何函数。

watch a talk on the event loop;观看关于事件循环的演讲; it helped me understand what is going on here, this was really confusing to me when I first started but understanding the event loop helped.它帮助我了解这里发生了什么,当我刚开始时,这对我来说真的很困惑,但了解事件循环有帮助。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM