Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array length incorrect

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?

like image 987
Timon Avatar asked Jul 24 '15 08:07

Timon


1 Answers

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.

like image 53
Denys Séguret Avatar answered Oct 12 '22 05:10

Denys Séguret