Math与Date对象详解

脑图
Math与Date对象详解_第1张图片

目录

  • 1 Math对象
    • 1.1 Math常用属性
      • 1.1.1 Math.PI
    • 1.2 Math常用方法
      • 1.2.1 [abs(x)](https://www.w3school.com.cn/jsref/jsref_abs.asp)
      • 1.2.2 [random()](https://www.w3school.com.cn/jsref/jsref_random.asp)
      • 1.2.3 取整
        • 向下取整
        • 向上取整
        • 四舍五入
      • 1.2.4 最值 [max(x,y)](https://www.w3school.com.cn/jsref/jsref_max.asp) 、 [min(x,y)](https://www.w3school.com.cn/jsref/jsref_min.asp)
      • 1.2.5 开方 [sqrt(x)](https://www.w3school.com.cn/jsref/jsref_sqrt.asp)
  • 2 Date
    • 2.1 构造函数
    • 2.2 年月日
    • 2.3 时分秒
    • 2.4 时间戳

1 Math对象


不是构造函数,直接使用,详情点击

1.1 Math常用属性


1.1.1 Math.PI


他表示的是我们的圆周率 $ \pi $

console.log(Math.PI) // 3.141592653589793

1.2 Math常用方法


1.2.1 abs(x)


返回数的绝对值

console.log(Math.abs(-9)) // 9

1.2.2 random()


返回 0 ~ 1 之间的随机数,包括0,不包括1

返回[n,m]区间中的数Math.random*(m-n) + n

按最小值最大值计算出来的,当抽到0的时候应该是最小值,而最小值是 n 所以加上 n

当抽到 1 的时候是最大值,最大值应该是 m ,因为前面加上 n 了,所以要减去 n

// 返回 [0,1)之间的随机小数
console.log(Math.random())
// 返回[3,15]之间的随机小数
console.log(Math.random()*(15-3) + 3 )

1.2.3 取整


向下取整

Math.floor :floor地板的意思,地板就是下面

向上取整

Math.ceilceil天花板的意思,天花板在上面

四舍五入

Math.round

// 向上取整
console.log(Math.ceil(5.1)) //6
// 向下取整
console.log(Math.floor(6.9)) //6
// 四舍五入
console.log(Math.round(4.4))//4
console.log(Math.round(4.5))//5

1.2.4 最值 max(x,y) 、 min(x,y)


函数可以传递多个参数,分别去参数的最大值和最小值

  • 没有参数返回-Infinity
  • 不能转化为数值的参数,返回NaN
console.log(Math.max(9,-4,2,6,1.2))//9
console.log(Math.min(9,-4,2,6,1.2))//-4
console.log(Math.max())//-Infinity
console.log(Math.max("Hello"))//NaN

1.2.5 开方 sqrt(x)


返回一个数的平方根

console.log(Math.sqrt(4)) // 2

2 Date


是一个构造函数,详情点击

2.1 构造函数


不传递参数

不传递参数返回的是当前的时间

console.log(new Date())
/* Wed Jul 15 2020 13:16:47 GMT+0800 (中国标准时间) */

传递参数

传递参数返回的是格式化后的时间

console.log(new Date("11/11/2011 11:11:11"))
/* Fri Nov 11 2011 11:11:11 GMT+0800 (中国标准时间) */

2.2 年月日


分别使用getFullYear(),getMonth(),getDate()方法来获取

注意月份少1

2.3 时分秒

分别使用getHours(),getMinutes(),getSeconds方法来获取

2.4 时间戳


  • 使用date.getTime()获得指定时间的时间戳
  • 使用Date.now(),获得当前时间的时间戳
var date = new Date("11/11/2011 11:11:11")
// 年月日
console.log(date.getFullYear()) // 2011
console.log(date.getMonth()) //10 注意这里的月份输出是少1的
console.log(date.getDate())// 11
// 时分秒
console.log(date.getHours()) // 11
console.log(date.getMinutes())// 11
console.log(date.getSeconds())// 11
// 时间戳
console.log(date.getTime()) // 1320981071000
console.log(Date.now())// 1594794375982

你可能感兴趣的:(ESMAScript)