7

I have an array filled with objects. It contains 23 items in total, however when I perform a .length on it, it returns 20.

// Get the new routes var array = PostStore.getPostList(); console.log(array.objects); console.log(array.objects.length); 

Image of what my console returns:

Array Length

What's going wrong here?

12
  • Is getPostList returning a promise? Commented Jul 24, 2015 at 8:58
  • Can you post PostStore data? Commented Jul 24, 2015 at 8:58
  • 1
    Take a look at my answer here about chrome console logging. Commented Jul 24, 2015 at 9:00
  • 1
    @RJK: That's not going to help. Commented Jul 24, 2015 at 9:01
  • 2
    You are correct. I think the array is being changed between the time I logged it and the time I opened it. Your solution seems to work. Marking it as an answer in a min. :) Commented Jul 24, 2015 at 9:10

1 Answer 1

7

The problem is probably that the array changed between the time you logged it and the time you opened it in the console.

To get the array at the logging time, clone it:

console.log(array.objects.slice()); console.log(array.objects.length); 

Note that this won't protect against the array element properties changing. If you want to freeze them too, you need a deep cloning, which is most often possible with

console.log(JSON.parse(JSON.stringify(array.objects.slice())); 

This won't work if the objects aren't stringifyable, though (cyclic objects, very deep objects, properties throwing exceptions at reading, etc.). In that case you'll need a specific cloning, like my own JSON.prune.log.

A alternative to logging is also, in such a case, to debug. Set a breakpoint and look at the objects while the code is stopped.

Sign up to request clarification or add additional context in comments.

4 Comments

While this probably is the case, its funny iv'e never ran into this issue before, I would ask is this a chrome condition or infact if you're using the array obj on 2 consecutive lines will it cause issues ?
Instead of doing all that cloning and slicing just print .toString()
@StoyanDekov But then you'll be unable to see everything
@Pogrindis All browsers are subject to this problem. The reason is they can't build a deep cloned representation of what you log because it would be much too heavy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.