js内置对象Math、Date

本篇介绍一些常用的内置对象方法

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文档:

Math - JavaScript | MDN (mozilla.org)

Date - JavaScript | MDN (mozilla.org)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值