js生成随机数/数组(marksheng)

39 篇文章 1 订阅
37 篇文章 4 订阅

生成范围内随机数

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


 

生成随机数组

简单的随机生成

```javascript
function randArray(len, min, max) {
    return Array.from({length:len}, v=> Math.floor(Math.random()*(max-min))+min);
}

function randArray2(len, min, max) {
    return Array(len).fill(1).map(v=> Math.floor(Math.random()*(max-min))+min);
}
```

生成随机数组

模拟微信红包。100块钱,分10份。设置时用的是元,实际按分算所以应该设置 scale = 100
10块钱分10份这种事就别玩了


/**
 * 生成随机数组
 * _total    总数,默认为100
 * _len        分len份,默认为10
 * _scale    缩放n倍输出,默认为1
 */
function randomFn(_total, _len, _scale){
    let total = _total || 100;
    let len = _len || 10;
    let scale = _scale || 1;
    let arr = [];
    
    for(let i = 0; i < len-1; i++){
        let temp = parseInt( Math.random() * total * scale + 1);
        while (arr.indexOf(temp) > -1){
           temp = parseInt( Math.random() * total * scale + 1);
        }
        arr[i] = temp;
    }

    arr.unshift(0);
    arr.push(total * scale);
    arr.sort((a,b)=>a-b);
    for(let j=0; j<len; j++){
        arr[j] = (arr[j+1] - arr[j]) / scale;
    }
    arr.length = len;
    return arr;
}
// 测试下 100分10分
var arr = randomFn();
// 合计正好100
arr.reduce((acc, cur)=> acc + cur);
```

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值