生成10个随机数(10-100),并将其从小到大排列的方法

<!DOCTYPE html >
< html lang= "en" >

< head >
< meta charset= "UTF-8" >
< meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
< meta http-equiv= "X-UA-Compatible" content= "ie=edge" >
< title >Document </ title >
</ head >

< body >

</ body >
< script >
// 1声明一个空数组用来存放数据;
var a = [];
// 2将生成随机数的代码通过for循环操作10遍
for ( let i = 0; i < 10; i++) {
// 包含0和100
var b = Math. round( Math. random() * 90 + 10);
// 2.1将生成的数值放进a数组里面
a. push( b);
}
// 定义一个函数为了让数据从小到大的排序
function c( f, g) {
return f - g;
}
// 输出的时候进行引用c
console. log( a. sort( c));
< / script >
</ html >

<!-- 以下为参考部分 -->
<!-- Math:数学对象,提供对数据的数学计算。
Math.random(); 返回0和1间(包括0,不包括1)的一个随机数。
Math.ceil(n); 返回大于等于n的最小整数。 用Math.ceil(Math.random()*10);时,主要获取1到10的随机整数,取0的几率极小。
Math.round(n); 返回n四舍五入后整数的值。 用Math.round(Math.random());可均衡获取0到1的随机整数。 用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。
Math.floor(n); 返回小于等于n的最大整数。 用Math.floor(Math.random()*10);时,可均衡获取0到9的随机整数 -->

猜你喜欢

转载自blog.csdn.net/weixin_41905935/article/details/80593537