I want to swap two arrays inside a 2D array, however JS seems to be doing that before my actual swap is happening.
This is for an algorithm I'm working on, providing each possible way to display a list of points. I have tried several ways of doing this, but the key problem keeps returning, and I've managed to crop it down to this peace of code:
var points = [[1,2],[10,20],[100,200]];
console.log(points);
var a = points[1][0];
var b = points[1][1];
points[1][0] = points[2][0];
points[1][1] = points[2][1];
points[2][0] = a;
points[2][1] = b;
console.log(points);
I know this code isn't close to being DRY, but it has the same problem: 'points' is logged to the console in the line after being declared, though in that log, it is already swapped? How is that possible, as there were no commands yet saying it to do so. How does JavaScript handle this peace of code? And why doesn't mine seem to be working?
**The expected output for the first log is: [[1,2],[10,20],[100,200]] **and for the second log: [[1,2],[100,200],[10,20]]
The StackOverFlow snipped runs it as it is expected, but Chrome runs it differently
I believe what's happening here is that the console is showing something like this (in Firefox):
But then you click to expand it to take a look inside the array, the items are swapped:
This is because the console is actually showing you a reference to the array, and since your algorithm modifies the original array in place, by the time you click to expand the element in console, the reference has been modified. Your code is fine, you might try using .toString()
or JSON.stringify
or even [...points]
to make sure what's output to the console in each line are different values and not a reference to the same value.
Running your exact algorithm with console.log(points.toString())
instead, I see this (again in Firefox):
And just for demonstration purposes, here's how you can simplify your code to do the same thing using destructured assignment:
var points = [[1, 2], [10, 20], [100, 200]];
console.log(points.toString());
[points[1], points[2]] = [points[2], points[1]];
console.log(points.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With