如何用javascript洗牌?

问题描述 投票:0回答:1
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 
}

我的老师教我如何洗牌,我除了都懂之外

let temp = array[currentindex];
    array[currentindex] = array[randomcards];
    array[randomcards] = temp}
   return array 

我不明白他为什么要写这个,有人可以解释一下这段代码的作用吗?

我尝试用谷歌搜索,但找不到任何资源可以清楚地解释它。

javascript arrays while-loop
1个回答
0
投票

这一切只是交换索引

currentindex
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

更简单的方法是使用 解构

[array[currentindex], array[randomcards]] = [array[randomcards], array[currentindex]]; // this is equivalent to the 3 lines above
© www.soinside.com 2019 - 2024. All rights reserved.