js 随机打乱数组

方法一. 利用 sort 排序,排序条件为:0.5 - Math.random()

    let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    Array.prototype.toRandom = function() {
        let tempArr = this.slice();
        tempArr.sort(() => 0.5 - Math.random());
        return tempArr;
    }

Math.random() 函数返回一个浮点, 伪随机数在范围[0,1)。
所以,得到一个两数之间的随机数,范围 [min,max):

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

得到一个两数之间的随机整数,包括两个数在内:

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; 
}

方法二. 让数组中的每一项与后面随机选中的项交换

    let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    Array.prototype.toRandom = function() {
        let tempArr = this.slice();
        let length = tempArr.length;
        for (let i = 0; i < length; i++) {
            let index = parseInt(Math.random() * (length - i)) + i;
            if (index != i) {
                let temp = tempArr[i];
                tempArr[i] = tempArr[index];
                tempArr[index] = temp;
            }
        }
        return tempArr;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • .写一个函数,返回从min到max之间的 随机整数,包括min不包括max function randomness...
    邢烽朔阅读 328评论 0 1
  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 7,637评论 1 118
  • 问答 数组方法里push、pop、shift、unshift、join、split分别是什么作用。(*) var ...
    风骨来客阅读 369评论 0 0
  • 我不是个美少女,也压根儿没有幻想过屠龙的少年。我猜想我的意中人总有一天会踩着七彩的云朵,披着金甲圣衣,然后仙气飘飘...
    窝书阅读 251评论 0 3