Math对象

it2025-10-07  7

Math对象

Math对象常用APIMath.PI---返回圆周率3.1415926...Math.ceil(x)----------对数值x进行向上取整Math.floor(x)--------对数值x进行向下取整Math.round(x)----对数值x进行四舍五入取整Math.abs(x)----------返回x的绝对值Math.pow(x,y)--------返回x的y次方Math.sqrt(x)----------返回x的平方根Math.min(a,b,c...)----返回abc...中的最小值Math.max(a,b,c... )---返回abc...中的最大值Math.random()---返回介于(0,1)之间的随机数random的案例

Math对象用于执行数学任务。 Math是一个内置对象,不需要创建,可以直接使用。

Math对象常用API

Math.PI—返回圆周率3.1415926…

Math.ceil(x)----------对数值x进行向上取整

console.log(Math.ceil(15.7));//16 console.log(Math.ceil(15.3));//16 console.log(Math.ceil(15.001));//16 console.log(Math.ceil(15.00));//15 console.log(Math.ceil(-4.3));//-4

Math.floor(x)--------对数值x进行向下取整

console.log(Math.floor(15.7));//15 console.log(Math.floor(15.3));//15 console.log(Math.floor(15.001));//15 console.log(Math.floor(15.00));//15 console.log(Math.floor(-4.3));//-5

Math.round(x)----对数值x进行四舍五入取整

Math.abs(x)----------返回x的绝对值

Math.pow(x,y)--------返回x的y次方

Math.sqrt(x)----------返回x的平方根

Math.min(a,b,c…)----返回abc…中的最小值

Math.max(a,b,c… )—返回abc…中的最大值

Math.random()—返回介于(0,1)之间的随机数

random的案例

1.如何得到 0 ~ 1 的随机整数[0,1]?

var random = Math.round(Math.random()); console.log(random);

2.如何得到 0 ~ 5 的随机整数[0,5]?

var random = Math.round(Math.random() * (5 - 0)) + 0; console.log(random);

3.生成区间随机整数

function randomInt(min, max) { return Math.round(Math.random() * (max - min)) + min; } console.log(randomInt(10, 30)); 写一个函数 randomCode() 生成6位随机验证码(数字、字母(大小)) function randomInt(min, max) { return Math.round(Math.random() * (max - min)) + min; } console.log(randomInt(10, 30)); function randomCode() { // 48-122 >57&&<65 >90&&<97 var arr = [1, 1, 1, 1, 1, 1]; for (var i in arr) { do { var ascii = randomInt(48, 122); } while ((ascii > 57 && ascii < 65) || (ascii > 90 && ascii < 97)); arr[i] = String.fromCharCode(ascii); } return arr.join(''); } console.log(randomCode()); 写一个函数 randomColor 生成随机的十六进制颜色值 # 6个字符 //0 1 2 3 4 5 6 7 8 9 a b c d e f style: .box { width: 200px; height: 100px; } html: <div class="box"></div> script: function randomInt(min, max) { return Math.round(Math.random() * (max - min)) + min; } console.log(randomInt(10, 30)); function randomColor() { var str = '0123456789abcdef'; var col = '#'; for (var i = 0; i < 6; i++) { var index = randomInt(0, 15); col += str[index]; } return col; } console.log(); var box = document.querySelector('.box'); box.style.backgroundColor = randomColor();
最新回复(0)