gpt4 book ai didi

javascript - 如何随机化(洗牌)JavaScript 数组?

转载 作者:行者123 更新时间:2023-11-30 06:21:48 25 4
gpt4 key购买 nike

我有一个这样的数组:

var arr1 = ["a", "b", "c", "d"];

我怎样才能随机化/随机化它?

最佳答案

事实上的无偏洗牌算法是 Fisher-Yates (aka Knuth) Shuffle .

你可以看到一个great visualization here (和原帖linked to this)

function shuffle(array) {
let currentIndex = array.length, randomIndex;

// While there remain elements to shuffle.
while (currentIndex != 0) {

// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;

// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}

return array;
}

// Used like so
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

更多信息 about the algorithm用过。

关于javascript - 如何随机化(洗牌)JavaScript 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52691211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com