let cards = ["A","2","3","4","5","7","8","9","10","J","Q","K"];
shuffle(cards);
console.log(cards);
function shuffle(array){
let currentindex = array.length;
while (currentindex !=0) {
let randomcards = Math.floor(Math.random()* array.length)
currentindex -=1;
let temp = array[currentindex];
array[currentindex] = array[randomcards];
array[randomcards] = temp}
return array
}
My teacher taught me how to shuffle cards , I can understand it all apart from
let temp = array[currentindex];
array[currentindex] = array[randomcards];
array[randomcards] = temp}
return array
I can’t understand why did he write this , can someone explain me how this code act pls ?
I’ve tried to google but can’t find any resource explain clearly about it.
2
Answers
All this does is swap the array items at index
currentindex
andrandomcards
.A simpler way to do this is with destructuring:
Imagine you have two cups: the first one contains water and the second one contains wine. You need to swap the drinks. Let’s call the first one A and the second one B. Currently, A has water and B has wine. If we want to swap the drinks, we need a third cup (C).
With this approach we swapped drinks. since your code is written in js you could use array descructuring: