-1

I'm console logging them in chrome, they appear like this:

(A) []

(B) (3) [{…}, {…}, {…}]

The inside of these arrays is identical when opening them in console. The difference is that I'm hard coding in the values for B and using

arrayA.push({
   ...
});

on an empty (arrayA = [];) for array A. Consequently when trying to access the elements in array A, arrayA[0] it returns undefined, compared to arrayB[0] which returns the intended value.

EDIT: here is a JSFiddle

fdsfdsgf
  • 35
  • 6
  • https://stackoverflow.com/questions/16484838/console-logarray-shows-different-array-contents-than-iterating-the-array-and-d – epascarello Aug 10 '17 at 14:37
  • Array A is empty. Array B is a list of three objects each containing whatever you've elided with those ellipses. I can't explain how you could possibly be winding up with an empty array after `push`ing something onto it; you'll need to show your actual code. [mcve] – Daniel Beck Aug 10 '17 at 14:40
  • @DanielBeck here is a [JSFiddle](https://jsfiddle.net/0u6zorau/2/) – fdsfdsgf Aug 10 '17 at 14:48

1 Answers1

0

Your fiddle shows what the problem is: async code. You're making an ajax call, and pushing the data onto the array after the call returns. Your console.log of the array happens before the ajax call returns, so the array is still empty at that time.

If you console.log the data inside the callback, you'll see the actual data. Highly simplified example:

var a = [];
$.getJSON('http://example.com', function(data) {
    a.push(data);  
    console.log(a); // now a contains data
});
console.log(a); // a is still empty, because the getJSON hasn't returned yet 
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53