skip to Main Content
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


  1. All this does is swap the array items at index currentindex and randomcards.

    let temp = array[currentindex]; // create a temp variable to store the value while it's being swapped
    array[currentindex] = array[randomcards]; // replace the first item with the 2nd item
    array[randomcards] = temp // replace the 2nd item with the 1st item from the temp variable
    

    A simpler way to do this is with destructuring:

    [array[currentindex], array[randomcards]] = [array[randomcards], array[currentindex]]; // this is equivalent to the 3 lines above
    
    Login or Signup to reply.
  2. 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).

    const temp = array[currentIndex]; // A => C
    array[currentIndex] = array[randomCards] // B => A
    array[randomCards] = temp; // C => A
    

    With this approach we swapped drinks. since your code is written in js you could use array descructuring:

    [array[currentindex], array[randomcards]] = [array[randomcards], array[currentindex]]; 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search