JavaScript基础总结(五)——Math对象

25次阅读

共计 657 个字符,预计需要花费 2 分钟才能阅读完成。

1、JavaScript 中的 Math 对象包括:
Math.min()最小值
Math.max()最大值
Math.ceil()向上取最小的整数
Math.floor() 向下取值
Math.round() 四舍五入
Math.abs()绝对值
代码如下:
// 最小值
var min=Math.min(1,2,3,5,0);
console.log(min); // 最小值为 0
// 最大值
var max=Math.max(0,-99,1,1.1);
console.log(max);// 最大值为 1.1
// 向上取整
var ceil=Math.ceil(12.01);
console.log(ceil);//13
// 向下取整
var floor=Math.floor(12.1);
console.log(floor);//12
// 四舍五入
// var round=Math.round(13.01);//13
var round=Math.round(13.56);//14
console.log(round);
// 绝对值
var abs=Math.abs(-15);
console.log(abs);//15
2、随机数例如下:
function stochastic(x,y){
// 随机数个数
var num=y-x+1; // 随机数为 6
var random=Math.floor(Math.random()*num+x);// 使用向下取整,随机数 * 随机数个数 + 最小值
console.log(random);
}
stochastic(5,10);
stochastic(8,99);

正文完
 0