JavaScript的 随机数方法 random()运用

304 阅读1分钟

随机数方法 random()

random() 方法可以随机返回一个小数,其取值范围是[0,1),

左闭右开 0 <= x < 1 随机数方法

random() 得到一个两数之间的随机整数,包括两个数在内

//0~1  ()>=0 ,<1)

        console.log(Math.random());

        //05 0~0.9 *5 Math.floor(0,4.50~4

        console.log(Math.floor(Math.random()*(5+1)));

        //Math.floor(Math.random()*(Max+1));

\
\


        //2~5 2.7       2           0~2

        console.log(2+Math.floor(Math.random()*(5-2+1)));

\


        //min+Math.floor(Math.random()*(Max-min+1))

\


        const studets=["张三","李四","赵谦","马六","黄渤"];

\


        console.log(studets.length);

\


        const index=(Math.floor(Math.random()*studets.length));

        console.log(studets[index]);

\


        const index1=(2+Math.floor(Math.random()*(studets.length-2)));

        console.log(studets[index1]);

\
\


        //封装随机函数

        function arrayRandomValue(array,start=1,end){

            end=end?end:array.length;

            start--;

            const index2=start+Math.floor(Math.random()*(end-start));

            return index2;

        }

        console.log(studets[arrayRandomValue(studets,3,4)]);