Math 对象 : JavaScript的一个内置对象
1.Math.PI 圆周率的值
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 </head> 8 <body> 9 <script> 10 console.log(Math.PI); 11 </script> 12 </body> 13 </html>
2. Math.max() , Math.min() 取最大值最小值
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 </head> 8 <body> 9 <script> 10 console.log(Math.max(1,2,3,4,5,6,7,8,9)); 11 console.log(Math.min(1,2,3,4,5,6,7,8,9)); 12 </script> 13 </body> 14 </html>
3. Math.abs() 取绝对值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> console.log(Math.abs(-9999)); console.log(Math.abs(9999)); </script> </body> </html>
4. Math.floor() 向下取整
Math.ceil() 向上取整
Math.round() 四舍五入取整
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> //math.floor() 向下取整 console.log(Math.floor(10.9)); console.log("==========================") //math.ceil() 向上取整 console.log(Math.ceil(20.2)); console.log("==============================") //math.round() 四舍五入取整 console.log(Math.round(4.4)); console.log(Math.round(4.5)); </script> </body> </html>
5. Math.random() 返回一个随机数 [0,1)之间的浮点数
返回两个数之间的一个随机整数,注意返回的这个随机数是不包含 max的,要想加上max,可以将(max - min)
修改为(max - min +1)
Math,floor( Math.random() *( max - min ) ) + min
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> function getRandom(min,max){ return Math.floor( Math.random() * (max - min) ) + min; } for(var i = 0;i <10;i++){ console.log(getRandom(1,10)); } </script> </body> </html>