Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - 如何随机化(随机播放)JavaScript数组?(How to randomize (shuffle) a JavaScript array?)

I have an array like this:

(我有一个像这样的数组:)

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

How can I randomize / shuffle it?

(如何随机/随机播放?)

  ask by Click Upvote translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.

(实际无偏混洗算法是Fisher-Yates(aka Knuth)混洗。)

See https://github.com/coolaj86/knuth-shuffle

(参见https://github.com/coolaj86/knuth-shuffle)

You can see a great visualization here (and the original post linked to this )

(您可以在此处看到出色的可视化效果 (以及与此链接相关的原始文章))

 function shuffle(array) { var currentIndex = 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 = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } // Used like so var arr = [2, 11, 37, 42]; arr = shuffle(arr); console.log(arr); 

Some more info about the algorithm used.

(有关使用的算法的更多信息。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...