生成指定num-start 个数组长度,值为start---num 的随机数组,不包括num这个值
function rand_arr(num,start) {
// 验证值 if(!arguments[0]) { console.log("请传入数组个数"); return; } if(!arguments[1]) { start=0; }else { start=typeof(start)=="number"?start:parseInt(start); } // 转型 num=typeof(num)=="number"?num:parseInt(num); // 判断值 if(start>=num) { start=0; } var arr=new Array(); for(var i=start;i<num;i++) { arr.push(i); } console.log(arr.sort(randomsort)); } // 随机排序 function randomsort() { return Math.random()>.5 ? -1 : 1; } // 调用 rand_arr(15,3);
给定最大最小值生成 指定个数的 随机数组【排序】,不包括最大值
function unique_rand(min,max,num,order) { // 验证值 if(!arguments[0] || !arguments[1]) { console.log("请传入max,min 值"); return; } // 转型 min=typeof(min)=="number"?min:parseInt(min); max=typeof(max)=="number"?max:parseInt(max); if(min==max) { console.log("min,max值相同"); } // 判断参数值 if(max<min) { max+=min; min=max-min; max=max-min; } max_num=max-min; if(!arguments[2] || max_num<num) { num=max-min; }else { num=typeof(num)=="number"?num:parseInt(num); } // 生成随机数组 var new_arr=new Array(); var rand_n; while(new_arr.length<num) { rand_n=Math.floor(Math.random()*(max_num))+min; // 生成一个随机数,给定范围 var off=true; for(i=0;i<new_arr.length;i++) { if(new_arr[i]!=rand_n) { off=true; }else { off=false; break; } } if(off) { new_arr.push(rand_n); } } // 数组排序 if(arguments[3]==true) { new_arr.sort(); } console.log(new_arr); } // 调用 unique_rand(23,10,5,true);
相关文章:js-随机产生一个由10个元素组成的数组