This is the weirdest thing I've ever encountered in my programming life.
self.walls = new Array();
self.walls = [];
console.log(self.walls); //Doesn't print an empty array, but an array that contains something
How is this possible? I set self.walls to an empty array in two ways, and it's still full of objects! I'm using the latest version of Google Chrome.
Edit: also, this is the only console.log() in the entire script.
3 Answers 3
console.log does not store the state of the object at the time of calling.
At a later point, you've overwritten the self.walls property, which is shown in the console.
If you want to log the true state at the time of executing, you can serialize the object:
// Works for primitives only:
console.log(JSON.parse(JSON.stringify(self.walls)));
// When the array contains another object, the shown referenced object might
// change
console.log(self.walls.concat()); // Or any other array-copying method.
3 Comments
console.log is supposed to take a string argument and print the string in the console.An array has a length, it has methods such as map, shift, unshift, pop, push and so on, and all of these show up in the console because they are properties of the array.
You probably don't see any property named 0, 1, or any other number, right? Those would be the actual array elements, if you'd defined any.
3 Comments
console.log doesn't pause execution.As Rob W explained, the console sometimes does not show the true representation of the array when it is called.
However, you mentioned emptying an array but your code ...
self.walls = new Array();
self.walls = [];
...is not emptying the array. It is assigning a new empty array to the property. To empty the array, you can use...
self.walls.length = 0;