【JavaScript】随机抽号,随机度更大(大*透)
作者:广树 | 时间:2017-5-29 10:41:19 | 分类 : JavaScript/jQuery/Vue
HTML
- <p class="caipiao_p"><span class="caipiao35">*</span><span class="caipiao35">*</span><span class="caipiao35">*</span><span class="caipiao35">*</span><span class="caipiao35">*</span><span>+</span><span class="caipiao12">*</span><span class="caipiao12">*</span></p>
- <button type="button" onClick="creat_caipiao_nums('caipiao35',arr_front,arr_front_cache)">抽选一个前区</button>
- <button type="button" onClick="creat_caipiao_nums('caipiao12',arr_back,arr_back_cache)">抽选一个后区</button>
- <button type="button" onClick="clear_nums()">清空</button>
CSS
- .caipiao_p span{
- padding-right:5px;
- }
JS
- function generate_randomx(count,nums_length) {
- //初始化数组
- var generated = new Array();
- //生成数组数
- var generatedCount = generated.length;
- //生成nums_length个随机数
- for(var i = 0 ; i < nums_length; i++){
- var candidate = Math.floor(Math.random() * count)+1;
- //如果生成一样的数字则重新生成
- for(var j = 0; j < generatedCount; j++) {
- if(candidate == generated[j]){
- candidate = Math.floor(Math.random() * count)+1;
- j= -1;
- }
- }
- generated[i] = candidate;
- generatedCount++;
- }
- return generated;
- }
- function creat_nums(caipiao_span,arr){
- //写入数字
- var caipiao_span = document.getElementsByClassName(caipiao_span);
- //获取HTML
- for(var i = 0 ; i < arr.length; i++){
- var arr_nums = arr[i];
- if(arr_nums<10){
- arr_nums = '0'+String(arr[i]);
- //如果数字小于10,自动前面部0
- }else{
- arr_nums = String(arr[i])
- }
- caipiao_span[i].innerText = arr_nums;
- }
- }
- function sortNumber(a, b){
- //数组从小到大排列
- return a - b
- }
- var arr_front = generate_randomx(35,35);
- var arr_back = generate_randomx(12,12);
- var arr_front_cache = [];
- var arr_back_cache = [];
- //初始化数据
- function creat_caipiao_nums(caipiao_span,arr_type,arr_type_cache){
- //每次点击随机从上面的数组中抽选一个数添加到缓存数组中,并剔除掉选中的数组。
- var length_nums = arr_type.length;
- if(arr_type_cache.length<document.getElementsByClassName(caipiao_span).length){
- var t = Math.floor(Math.random() * length_nums);
- arr_type_cache.push(arr_type[t]);
- arr_type_cache.sort(sortNumber);
- arr_type.splice(t,1);
- creat_nums(caipiao_span,arr_type_cache);
- console.log(arr_type_cache);
- console.log(arr_type);
- console.log(t);
- }
- }
- function clear_html(caipiao_span){
- //清空HTML内容
- for(var i = 0 ; i < caipiao_span.length; i++){
- caipiao_span[i].innerText = '*';
- }
- }
- function clear_nums(){
- //重置HTML与数组
- arr_front = generate_randomx(35,35);
- arr_back = generate_randomx(12,12);
- arr_front_cache = [];
- arr_back_cache = [];
- clear_html(document.getElementsByClassName('caipiao35'));
- clear_html(document.getElementsByClassName('caipiao12'));
- console.log(arr_front);
- console.log(arr_back);
- console.log(arr_front_cache);
- console.log(arr_back_cache);
- }
赞一个0
2018-12-19 15:20