“随机数”函数的 ES6 实现

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

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 < len) {
        rdmString += (Math.random() * 37 | 0).toString(36);
   }
   return rdmString;
}
const genRandomString = len => {
    const text = 'abcdefghijklmnopqrstuvwxyz0123456789';
    const rdmIndex = text => Math.random() * text.length | 0;
    let rdmString = '';    
    for(; rdmString.length < len; rdmString += text.charAt(rdmIndex(text)));
    return rdmString;
}

转载于:https://www.cnblogs.com/wenqiangit/p/10227317.html

你可能感兴趣的:(“随机数”函数的 ES6 实现)