问题
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
回答1:
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());
回答2:
p.s.w.g is correct, this has to do with Chrome's lazy eval of arrays for things like console.log. Here's more detail: Is Chrome's JavaScript console lazy about evaluating arrays?
来源:https://stackoverflow.com/questions/54697152/how-to-swap-two-elements-inside-of-a-2d-array-in-javascript-confused-about-wha