本篇介绍一些常用的内置对象方法
Math
Math内置对象,提供一系列与数学运算相关的属性和方法
console.log(typeof Math); // object
console.log(Math.PI); //3.1415926
Math.abs()
// 绝对值
console.log(Math.abs(-5)); // 5
Math.ceil()
// 向上取整
console.log(Math.ceil(10.1)); // 11
console.log(Math.ceil(-10.1)); // -10
Math.floor()
// 向下取整
console.log(Math.floor(10.9)); // 10
console.log(Math.floor(-10.9)); // -11
Math.max()
// 取最大值
console.log(Math.max(1,2,3,4)); // 4
Math.min()
// 取最小值
console.log(Math.min(1,2,3,4)); // 1
Math.round()
// 四舍五入
console.log(Math.round(10.6)); // 11
console.log(Math.round(-10.6)); // -10
Math.random()
// 产生一个随机数,范围是0到1,0<随机数<=1
console.log(Math.random());
Date
Date内置对象,提供一系列获取日期时间的方法
// 使用日期前需要创建日期对象
const date = new Date();
getFullYear()
// 年,完整年份
console.log(date.getFullYear()); // 2023
getMonth()
// 月,0-11, 0表示1月
console.log(date.getMonth()); // 10
getDate()
// 日,当月的第几日
console.log(date.getDate()); // 9
getHours()
// 小时
console.log(date.getHours()); // 8
getMinutes()
// 分钟
console.log(date.getMinutes()); // 58
getSeconds()
// 秒钟
console.log(date.getSeconds()); // 10
自定义日期
// 通过给 new Date 传入时间字符串来自定义一个日期对象
const d = new Date('2024-1-1 18:00:00');
consle.log(d.getFullYear()); // 2024
时间戳
// 时间戳,1970年1月1日到当前时间经历的毫秒数
console.log(+new Date()); // 1700445335125
console.log(Date.now()); // 1700445335125
const d = new Date();
console.log(d.getTime()); // 1700445335125
封装日期函数
// 封装一个返回当前时间的函数
function getTime(){
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth();
const day = date.getDate();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
if(hours < 10) hours = `0${hours}`;
if(minutes < 10) minutes = `0${minutes}`;
if(seconds < 10) seconds = `0${seconds}`;
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
console.log(getTime()); // 2023-10-20 10:03:16
MDN文档: