javascript帶範圍的隨機整數生成
阿新 • • 發佈:2018-04-09
++ num mint n) ber sub push fun div
//生成一個整數隨機數,並且範圍為[min,max) function randomInt(min,max){ if(min < 0 || max <0){ throw "不支持負數"; } var number = parseInt(Math.random().toString().substring(2)); return number%(max-min) + min; }
//生成count個不重復的隨機數,並且範圍為[scope_min,scope_max) function randomIntNoRepeat(count,scope_min,scope_max){var numbers = []; if(scope_max - scope_min < count){//範圍不正確 throw "範圍不正確"; } for(var i = 0; i < count;i ++){ var number = randomInt(scope_min,scope_max); while(numbers.includes(number)){ number = randomInt(scope_min,scope_max); } numbers.push(number); }return numbers; }
javascript帶範圍的隨機整數生成