javascript 数组 shuffle 洗牌 打乱顺序

* php shuffle 打乱数组顺序

Array.prototype.shuffle = function () {
    "use strict";
    var a = [], b = [], n = this.length, i, j, seq;
    // @b: a[i] element exists?
    for (i = 0; i < n; i++) {
        b[i] = 0;
    }

    function _getIndex(b, seq) {
        var n = b.length;
        for (i = 0; ; i = (i+1)%n) {
            if (!b[i]) {
                if (seq===0) {
                    break;
                }
                seq--;
            }
        }
        return i;
    }

    while (n-->0) {
        seq = Math.floor(3*this.length * Math.random());
        j = _getIndex(b, seq);
        a.push(this[j]);
        b[j] = 1;
    }

    return a;
};

  

test:

// var aa = ['DevTools', 'PHP', 'PHP_Framework', 'EclipsePDT', 'Laravel', 'PHPStorm', 'ThinkPHP5'];
var aa = [0,1,2,3,4,5,6,7,8,9];
var n = 1000;

if (typeof window === "undefined") {
    while (n--) {console.log(aa.shuffle());}
} else {
    while (n--) {document.write("<p>["+aa.shuffle().toString()+"]</p>");}
}

 有了这个方法,以后方便测试数组排序的问题。

猜你喜欢

转载自blog.csdn.net/fareast_mzh/article/details/81463816