JavaScript隨機打亂數組順序之隨機洗牌演算法_javascript技巧

來源:互聯網
上載者:User

假如有一個數組是這樣子:

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

如何隨機打亂數組順序,也即洗牌。

有一個比較廣為傳播的簡單隨機演算法:

function RandomSort (a,b){ return (0.5 - Math.random()); }

實際證明上面這個並不完全隨機。

隨便一搜網上太多這種東西了,看一下stackoverflow上的一個高分回答,答案出自github上。

knuth-shuffle
The Fisher-Yates (aka Knuth) shuffle for Browser and Node.JS

下面一起看看上面說的這個演算法,代碼如下:

/*jshint -W054 */(function (exports) {'use strict';// http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-arrayfunction 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;}exports.knuthShuffle = shuffle;}('undefined' !== typeof exports && exports || 'undefined' !== typeof window && window || global));

作者推薦使用瀏覽器寫法:

(function () {'use strict';var a = [2,11,37,42], b;// The shuffle modifies the original array// calling a.slice(0) creates a copy, which is assigned to bb = window.knuthShuffle(a.slice(0));console.log(b);}());

Nodejs:

npm install -S knuth-shuffle(function () {'use strict';var shuffle = require('knuth-shuffle').knuthShuffle, a = [2,11,37,42], b;// The shuffle modifies the original array// calling a.slice(0) creates a copy, which is assigned to bb = shuffle(a.slice(0));console.log(b);}());

還有其它從這個演算法中變形去的,比如下面這個for迴圈的。其它的就不說了。

/*** Randomize array element order in-place.* Using Durstenfeld shuffle algorithm.*/function shuffleArray(array) {for (var i = array.length - 1; i > 0; i--) {var j = Math.floor(Math.random() * (i + 1));var temp = array[i];array[i] = array[j];array[j] = temp;}return array;}

使用ES2015(ES6)

Array.prototype.shuffle = function() {let m = this.length, i;while (m) {i = (Math.random() * m--) >>> 0;[this[m], this[i]] = [this[i], this[m]]}return this;}

使用:

[1, 2, 3, 4, 5, 6, 7].shuffle();

發現中文搜尋隨機演算法一大堆,但究竟是不是完全隨機,效率和相容性都有待考究,建議後面如果有需要用到隨機打亂數組元素,可以用上面這個。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.