js内置对象-Math对象

内置对象:就是js语法中,内置的一些对象 提供很多的属性和方法,可以直接用
1、Math对象:提供了一系列和数学相关的属性和方法
(1)PI => Math.pI
(2)min,max 求最大值和最小值 =>Math.max (); Math.min ()


(3)取整:ceil天花板函数,向上取整,取大的那个值 => Math.ceil()
floor地板函数,向下取整,取小的那个值 => Math.floor()
round四舍五入 离哪个近,取哪个 => Math.round()

例题:

// console.log(Math.ceil(1.1)); // 2
// console.log(Math.ceil(1.9)); // 2
// console.log(Math.ceil(-1.1)); // -1
// console.log(Math.ceil(-1.9)); // -1

// console.log(Math.floor(1.1)); // 1
// console.log(Math.floor(1.9)); // 1
// console.log(Math.floor(-1.1)); // -2
// console.log(Math.floor(-1.9)); // -2

// console.log(Math.round(1.1)); // 1
// console.log(Math.round(1.9)); // 2
// console.log(Math.round(-1.1)); // -1
// console.log(Math.round(-1.9)); // -2

(4)随机数:random随机数 [ 0,1 ) => Math.random[ 0,1 ) 可以取到0,取不到1
随机一个整数范围:parseInt(Math.random()* (N+1))

例题:

// 公式: parseInt(Math.random() * (N+1)) 求0~N的随机整数

// 随机颜色 rgb(255, 255, 255); 颜色数值0~255

var colorA = parseInt(Math.random() * 256);
var colorB = parseInt(Math.random() * 256);
var colorC = parseInt(Math.random() * 256);
var str = "rgb(" + colorA + "," + colorB + "," + colorC + ")";

// 随机换肤效果, 给body随机设置背景色
document.body.style.backgroundColor = str;


(5)绝对值 abs=> Math.abs ()

console.log(Math.abs(1)); // 1
console.log(Math.abs(-1)); // 1


(5)求次方 pow=> Math.pow ()
(5)求开方 sprt=> Math.sprt ()

猜你喜欢

转载自www.cnblogs.com/hhmmpp/p/10992166.html