js中取2-32间的随机数组成自定义数组

function f(n){
        //大于数组长度时,取数组长度
    if(n>31)n=31;
    var number=[];
    while(n){
        //随机数的选取方法31为所需的数组长度
       var num=Math.floor(Math.random() * 31)+2;
        //数组查重的方法
       if(number.indexOf(num)<0){
           number.push(num);
           n--;
       }
    }
    console.log(number.sort());//用于观察数组
    console.log(number)
}

f(32)//只能取到数组长度的数组

取随机数的方法适用于从数组中随机获取内容,将随机数作为数组的下标即可

猜你喜欢

转载自blog.csdn.net/Lisunlight/article/details/82771895