持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第28天,点击查看活动详情
内置对象是指在JavaScript中,存在许多已经定义好的对象,这些对象共同组成了JavaScript的内置对象。
一、Math对象
Math对象不是构造函数,它封装了常用的数学属性和方法,以静态成员的方式提供跟数学相关的运算。常用的Math属性和方法有:
Math.E
获取欧拉常数e(基数)
console.log(Math.E); //2.718281828…
Math.PI
返回圆周率,一个圆的周长和直径之比,约等于3.14159。
console.log(Math.PI); //3.141592653...
Math.exp(x)
返回e的x次幂。e 代表自然对数的底数,其值近似为 2.71828。
console.log(Math.exp(-1)); //0.36787944117144233
Math.random()
返回一个0到1之间的随机数浮点数,包括0不包括1。
console.log(Math.random()); //0.9401643465262124
Math.floor(x)
返回一个对参数数值进行向下取整的数值。
console.log(Math.floor(Math.PI)); //3
Math.ceil(x)
返回一个对参数数值进行向上取整的数值。
console.log(Math.ceil(Math.PI)); //4
Math.round(x)
返回一个对参数数值四舍五入取整的数值。
console.log(Math.round(Math.E)); //3
Math.max(x1,x2,..,xn)
返回参数中的最大值,可以传多个参数进行比较,也可以传入数字数组然后通过...解构进行比较
console.log(Math.max(1, 3, 5, 2, 9, 55, 88, 12, 15, 7)); //88
var arr = [1, 3, 5, 2, 9, 55, 88, 12, 15, 7];
console.log(Math.max(...arr)); //88
Math.min(x1,x2,..,xn)
返回参数中的最小值,可以传多个参数进行比较,也可以传入数字数组然后通过...解构进行比较
console.log(Math.min(1, 3, 5, 2, 9, 55, 88, 12, 15, 7)); //1
var arr = [1, 3, 5, 2, 9, 55, 88, 12, 15, 7];
console.log(Math.min(...arr)); //1
console.log(Math.E); //2.718281828…
Math.abs(x)
返回一个参数数值的绝对值。
console.log(Math.abs(-22)); //22
Math.sqrt(x)
返回一个参数数值的平方根。
console.log(Math.sqrt(25)); //5
Math.pow(b, e)
返回参数b为基数的e次幂结果。
console.log(Math.pow(2, 3)); //8
Math.sin(x)
返回参数数值的正弦值
console.log(Math.sin(90 * Math.PI / 180)) // 1
Math.cos(x)
返回参数数值的余弦值
console.log(Math.cos(0 * Math.PI / 180)) // 1
Math.tan(x)
返回一个某个角的正切的数字。
console.log(Math.tan(90)) // -1.995200412208242
二、Date对象
Date是JavaScript中负责处理日期相关的内置对象。Date和Math不一样,Date既是JavaScript的内置对象,它本身又是构造函数,所以我们可以使用Date创建一个日期对象,并使用这个对象来调用Date中的属性和方法。
创建Date对象
var date = new Date();
console.log(date); //Thu Jun 23 2022 15:21:06 GMT+0800 (中国标准时间)
date = new Date('2022-06-01');
console.log(date); //Wed Jun 01 2022 08:00:00 GMT+0800 (中国标准时间)
date = new Date(2022,6,1); //Fri Jul 01 2022 00:00:00 GMT+0800 (中国标准时间)
通过
new Date()创建的时间对象是一个集合“星期 月份 日期 年份 时:分:秒 时间格式”的字符串,往往不能直接使用。
获取日期的毫秒
var date = new Date();
console.log(date.valueOf()); //1655969495439
console.log(date.getTime()); //1655969495439
Date.getFullYear()
返回四位数的年份
var date = new Date();
console.log(date.getFullYear()); //2022
Date.getMonth()
返回月份,从 0 开始,即 0 ~ 11
var date = new Date();
console.log(date.getMonth()); //5
Date.getDate()
返回当前月的第几天
var date = new Date();
console.log(date.getDate()); //23
Date.getDay()
返回星期几,从 0 开始,0 表示周日,然后按照周一到周六排序,6 表示周六
var date = new Date();
console.log(date.getDay()); //4
Date.getHours()
返回当前的小时数,从 0 开始,即 0 ~ 23
var date = new Date();
console.log(date.getHours()); //15
Date.getMinutes()
返回当前分钟数,从 0 开始,即 0 ~ 59
var date = new Date();
console.log(date.getMinutes()); //41
Date.getSeconds()
返回当前秒数,从 0 开始,即 0 ~ 59
var date = new Date();
console.log(date.getSeconds()); //12
Date.getMilliseconds()
返回当前毫秒数,从 0 开始,即 0 ~ 999
var date = new Date();
console.log(date.getMilliseconds()); //88