JavaScript基础之Math、Data对象,小白都会

13 阅读1分钟

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

//Math.floor()

console.log(Math.floor(3.2)); //3

console.log(Math.floor(-3.1)); //-4

//注意负数向下取整数字变大

//Math.ceil()

console.log(Math.ceil(3.6)); //4

console.log(Math.ceil(-4.1)); //-4

//Math.round()

console.log(Math.round(3.2)); //3

console.log(Math.round(-2.4)); //-2

1.2Math.random()

  • Math.random() 方法可以随机返回一个小数,其取值范围是 [0,1)

  • 得到一个两数之间的随机整数,包括第一个数,不包括第二个数

  • 猜数字小游戏~~

2.Data()日期对象

===========================================================================

  • Date 对象和 Math 对象不一样,他是一个构造函数,所以我们需要实例化后才能使用

  • Date 实例用来处理日期和时间

2.1Date()方法的使用

2.1.1获取当前时间必须实例化
2.1.2Date()构造函数的参数
  • 如果Date()不写参数,就返回当前时间

  • 如果Date()里面写参数,就返回括号里面输入的时间

2.2日期格式化

我们想要 2022-6-6 08:08:08 格式的日期,要怎么办?

这需要获取日期指定的部分,所以我们要手动的得到这种格式

| 方法名 | 说明 | 代码 |

| --- | --- | --- |

| getFullYear() | 获取当年 | Obj.getFullYear() |

| getMonth() | 获取当月(0-11) | Obj.getMonth() |

| getDate() | 获取当天日期 | Obj.getDate() |

| getDay() | 获取星期几(周日0到周六6) | Obj.getDay() |

| getHours() | 获取当前小时 | Obj.getHours() |

| getMinutes() | 获取当前小时 | Obj.getMinutes() |

| getSeconds() | 获取当前秒钟 | Obj.gerSeconds() |

2.3获取日期的总的毫秒形式

  • date.valueOf() :得到现在时间距离1970.1.1总的毫秒数

  • date.getTime() :得到现在时间距离1970.1.1总的毫秒数