Math对象属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math对象属性</title>
</head>
<body>
<script>
// 自然对数的基数e的值
console.log(Math.E); //2.718281828459045
//10为底的自然对数
console.log(Math.LN10); //2.302585092994046
//2为底的自然对数
console.log(Math.LN2); //0.6931471805599453
//以2为底的e的对数
console.log(Math.LOG2E); //1.4426950408889634
//以2为底的e的对数
console.log(Math.LOG10E); //0.4342944819032518
//π的值
console.log(Math.PI); //3.141592653589793
// 1/2的平方根
console.log(Math.SQRT1_2); //0.7071067811865476
// 2的平方根
console.log(Math.SQRT2); //1.4142135623730951
</script>
</body>
</html>
min()和max()
<script>
//min()方法用于确定一组数中的最小值,max()方法用于确定一组数中的最大值
let max = Math.max(1, 3, 5, 10);
console.log(max); //10
let min = Math.min(1, 3, 5, 10);
console.log(min); //1
//看完上面的API方法,再用原生js手写下
let num = [1, 5, 3, 2, 10];
let flag = num[0];
for (let i = 1; i < num.length; i++) {
if (num[i] > flag) {
flag = num[i]
}
}
console.log(flag); //10
//数组中使用API求最大值和最小值可以使用展开运算符
let arr = [5, 1, 21, 15, 10];
console.log(Math.max(...arr)); //21
console.log(Math.min(...arr)); //1
</script>
舍入方法
<script>
// 四种将小数舍入为整数的方法
// Math.ceil()向上取整
console.log(Math.ceil(25.9)); //26
console.log(Math.ceil(25.5)); //26
console.log(Math.ceil(25.1)); //26
//Math.floor()向下取整
console.log(Math.floor(25.9)); //25
console.log(Math.floor(25.5)); //25
console.log(Math.floor(25.1)); //25
//Math.round()四舍五入
console.log(Math.round(25.4)); //25
console.log(Math.round(25.5)); //26
//Math.fround()返回最接近的单精度(32位)浮点数
//可以在二进制中精确显示的数字32位和64位的值相同
console.log(Math.fround(25.9)); //25.899999618530273
console.log(Math.fround(25.5)); //25.5
//如果参数非数字结果为NaN
console.log(Math.fround('abc')); //NaN
</script>
Math.random随机数
<script>
//Math.random()随机数
console.log(Math.random()); //这里输出0~1范围内的随机数(浮点数,整数),包含0但不包含1
//获取1~10之间的一个随机数,包含1和10
function Math0_10() {
return Math.floor(Math.random() * 10 + 1);
}
console.log(Math0_10());
//获取2~10之间的一个随机数,包含2和10;
function Math2_10() {
return Math.floor(Math.random() * 9 + 2);
}
console.log(Math2_10());
//获取一个两数之间的随机数,包含最小值,不包含最大值
function getRandomInt(min, max) {
//这里和random相乘时一定要加括号,不加括号就会出现结果为0的情况
return Math.floor(Math.random() * (max - min)) + min;
}
console.log(getRandomInt(1, 5));
//获取一个两数之间的随机数,包含最小值和最大值
function getRandomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
console.log(getRandomIntInclusive(1, 5));
</script>