I've ran into something in JavaScript
that goes completely against my intuitions. I first define a function, Shuffle(Input_array)
, that randomizes the order of an array. I then define an array, Words
, print it to the console, and then print the result from Shuffle(Words)
.
This is the code:
<script>
function Shuffle(Input_array) {
var currentIndex = Input_array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = Input_array[currentIndex];
Input_array[currentIndex] = Input_array[randomIndex];
Input_array[randomIndex] = temporaryValue;
}
return Input_array;
}
var Words = [["I","think"],["this","is"],["very","strange"]];
console.log(Words);
console.log(Shuffle(Words));
</script>
When running this script, both my calls generate the same output, namely a shuffled array. When commenting out the last console.log
command, however, the array is printed in the order I defined it.
How is this possible? It seems like the first console.log
output is affected in whatever happens in the second one.
It should be noted that this doesn't happen if I define my array in a 1D fashion, for example var Words = ["This", "actually", "works"];
. I don't know if my function somehow can't handle 2D-arrays, but this shouldn't matter at all, since a later function call shouldn't be able to affect an operation predating it.