I was try to visualize a bubble sort with JS.I use a binary array to save each changed array.But in the binary array i only get array which has been sorted.
var arr = [1, 5, 3, 7, 2];
var newArray = [];
for (var i = 0; i < arr.length - 1; i++) {
for (var j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
arr[j] = arr[j] + arr[j + 1];
arr[j + 1] = arr[j] - arr[j + 1];
arr[j] = arr[j] - arr[j + 1];
console.log(arr);
newArray.push(arr);
}
}
}
I can't understand why i get the right result in the loop when i console arr[],but the newArray is [1, 2, 3, 5, 7],[1, 2, 3, 5, 7],[1, 2, 3, 5, 7],[1, 2, 3, 5, 7].
Why in the same scope the console and the push function get the different results?
How can i get the correct binary array?
i'm a newbie and completely confused about it.Does someone know the reason? Thank you
arr. In JavaScript, arrays are reference types, i.e. the array is not copied when you pass it to a function or assign it to a variable. Here is a simple example to demonstrate the issue:var arr = [1,2,3]; console.log(arr); /*1,2,3*/ arr[0] = 4; console.log(arr); /*4,2,3*/. The secondconsole.logshows a different array because I changedarr.newArray. You end up with the same array multiple times innewArrayso, of course, they are all identical. You need to copy each member into a new array and push that ontonewArray