Reputation: 335
I am currently developing using Javascript and I came over a problem, I couldn't solve. I would say that I am very experienced in programming, but something like this never happened before and I couldn't fix it using friends or the internet.
In the code below I create a simple 2D array and fill every position with 0.1. Then I log the array, modify it and log it again. What would you expect to be the output? I would expect it to log an array filled with many 0.1s and log another array filled with many 0.1s and at position 1,2 it should be 100.
But the real outcome are two similar arrays. It gets even weirder when I comment the line out, where I edit the array. Then the output arrays are again the same, but without the modification. So the first log depends on code executed AFTER it. And that seems very very weird to me. I'va also tried putting the modificaction line in an 1 second timeout. Same results.
Thanks for help in advance.
let test = [];
for (let xx = 0; xx < 2; xx++) {
test.push([]);
for (let yy = 0; yy < 6; yy++) {
test[xx].push(0.1);
}
}
console.log(test);
test[1][2] = 100;
console.log(test);
Upvotes: -1
Views: 74
Reputation: 4020
Look at the snippet that was edited in your question. Your code works fine.
If you see twice the same array on your browser's console, it's because of how the browser's dev tool work. Arrays aren't printed to the console when you're doing console.log(test)
, their reference are printed there. And then you "expand" the content of the array. Since you logged twice the same reference, they point to the same value.
If you logged console.log(test.toString())
instead, you'd see that the two logged values are different.
For instance, on Chrome :
Before expanding :
After expanding :
Upvotes: 1
Reputation: 2587
console.log
will have different behaviour about async/sync.
For more information: console.log() async or sync?
You can achieve different output using promises or async/await
let test = [];
for (let xx = 0; xx < 2; xx++) {
test.push([]);
for (let yy = 0; yy < 6; yy++) {
test[xx].push(0.1);
}
}
Promise.resolve(console.log(test)).then(() => {
test[1][2] = 100;
}).then(()=>{
console.log(test);
})
Or using async/await
let test = [];
for (let xx = 0; xx < 2; xx++) {
test.push([]);
for (let yy = 0; yy < 6; yy++) {
test[xx].push(0.1);
}
}
(async() => {
await console.log(test)
test[1][2] = 100;
await console.log(test);
})();
Upvotes: 0
Reputation: 82
Whenever you do console.log(someObject)
, browser outputs the live view of the object; which means any mutation you make to that object, updates the console output.
Instead serialize the object with JSON.stringify(someObject)
and then console.log
it. This gives you snapshot of that object, at the time of serialization. But you have to be careful in that, someObject
may have circular reference, and few other gotchas, which would create problems during serialization.
See https://developer.mozilla.org/en-US/docs/Web/API/Console/log
Upvotes: 0