ITPub博客

首页 > IT职业 > IT职场 > “随机数”函数的 ES6 实现

“随机数”函数的 ES6 实现

IT职场 作者:reay 时间:2021-09-09 09:07:02 0 删除 编辑

生成一个指定长度的数字数组

const getNumArray = len => [...new Array(len).keys()];
const getNumArray = len => Array.from({length: len}, (v, k) => k);

随机从数组中获取一个元素

const randomItem = items => items[Math.random() * items.length | 0];

生成一个特定范围内的随机数

const genRandom = (min, max) => (Math.random() * (max - min + 1) | 0) + min;

随机打乱数组元素的顺序

const shuffle = items => items.sort(() => Math.random() - 0.5);
const shuffle = items => {
    for (var i = items.length-1; i >=0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        [items[j], items[i]] = [items[i], items[j]];
    }
    return items;
}

生成一个随机的数字字母字符串

const genRandomString = len => {
    let rdmString = '';
    while(rdmString.length 
const genRandomString = len => {
    const text = 'abcdefghijklmnopqrstuvwxyz0123456789';
    const rdmIndex = text => Math.random() * text.length | 0;
    let rdmString = '';    
    for(; rdmString.length 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1075/viewspace-2799648/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    0
  • 访问量
    953