ceil
ceil() 对数进行上舍入
Math.ceil(25.1) =>26
Math.ceil(25.9) =>26
负数-号后面的数字越大 值越小
Math.ceil(-25.9) => -25 因为-25比-25.9的值要大
floor
floor() 对数进行下舍入 等于帮你把小数点后面的去掉了
Math.floor(25.9) =>25
Math.floor(25.1) =>25
Math.floor(25.16) =>25
负数-号后面的数字越大 值越小
Math.floor(-25.4) => -26 因为-26比-25.4的值要小
round
round() 把数四舍五入为最接近的数
Math.round(25.6) => 26
Math.round(25.4) => 25
Math.round(-25.4) => -25
Math.round(-25.6) => -26
Math.round(25.5) => 26
★特殊点 满足两个条件 第一个是负数 第二个小数位是5
Math.round(-25.5) => -25
document.write( Math.round(-25.5) );
random
random() 返回0.0~1.0之间的随机数 包括0,但是不包括1
document.write( Math.random() );
练习: 随机出现 1-10 之间的数 包括1 不包括10
公式 Math.floor( Math.random()*(max-min) ) + min
document.write( Math.floor(Math.random()*(10-1)) + 1 );
随机出现 2-10 之间的数 包括2 也包括10
公式 Math.floor( Math.random()*(max-min+1) ) + min
document.write( Math.floor(Math.random()*(10-2+1)) + 2 );
使用Math对象随机产生10到100的十个数字(包括10 也包括100), 并对这十个随机数排重
let arr1 = []; /* 用来存随机数
let arr2 = []; /* 用来存放去重后的数据
for(var i=0;i<10;i++){
包括10 也包括100 */
arr1.push( Math.floor( Math.random()*(100-10+1) )+10 );
不包括10 也不包括100 取10-100之间的 */
arr1.push( Math.floor( Math.random()*(99-11+1) ) + 11 );
1-10 不包括 1 和10 */
arr1.push( Math.floor( Math.random()*(9-2+1) ) + 2 );
}
for(var j=0;j<10;j++){
if(arr2.indexOf(arr1[j])==-1){
arr2.push(arr1[j])
}
}
arr2.sort(function(a,b){
return a-b;
})
改成冒泡排序
for(var a in arr2){
for(var b in arr2){
/后一个数比前一个数大的情况下
if(arr2[a]<arr2[b]){
先存下小的值
var temp = arr2[a];
arr2[a] = arr2[b];
arr2[b] = temp;
}
}
}
10到100的十个数字(不包括10 也不包括100 取10-100之间的)
console.log(arr2);
使用Math对象随机产生10到100的十个数字, (不包括100)并对这十个随机数排序
let arr = [];
for(var i=0;i<10;i++){
let num = Math.floor( Math.random()*(100-10) ) + 10;
arr.push(num)
}
arr.sort(function(a,b){
return a - b;
})
console.log(arr);