1.Math对象
Math是 JavaScript 的原生对象,提供各种数学功能。
1.1 Math.abs()
Math.abs 方法返回参数值的绝对值
Math.abs(1) // 1
Math.abs(-1) // 1
1.2 Math.max(),Math.min()
Math.max 方法返回参数之中最大的那个值,Math.min 返回最小的那个 值。
如果参数为空, Math.min 返回 Infinity , Math.max 返回 -Infinity 。
Math.max(2, -1, 5) // 5
Math.min(2, -1, 5) // -1
Math.min() // Infinity
Math.max() // -Infinity
1.3 Math.floor(),Math.ceil()
Math.floor 方法返回小于参数值的最大整数
Math.floor(3.2) // 3
Math.floor(-3.2) // -4
Math.ceil 方法返回大于参数值的最小整数
Math.ceil(3.2) // 4
Math.ceil(-3.2) // -3
1.4 Math.random()
Math.random() 返回0到1之间的一个伪随机数,可能等于0,但是一定小于1
Math.random() // 0.28525367438365223
公式如下:任意范围的随机数生成函数如下
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
getRandomArbitrary(5, 10)
例题:
function ToInteger(x) {
x = Number(x);
return Math.floor(Math.abs(x));
}
ToInteger(-10.4); // 向下取整:10
2.Date对象
Date 对象是 JavaScript 原生的时间库。它以1970年1月1日00:00:00 作为时间的零点,可以表示的时间范围是前后各1亿天(单位为毫 秒)
2.1 Date.now()
Date.now 方法返回当前时间距离时间零点(1970年1月1日 00:00:00 UTC)的毫秒数,相当于 Unix 时间戳乘以1000
Date.now(); // 1635216733395
2.2 时间戳
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间 1970年01月01日08时00分00秒)起至现在的总秒数。
格林威治和北京时间就是时区的不同
Unix是20世纪70年代初出现的一个操作系统,Unix认为1970年1月 1日0点是时间纪元。JavaScript也就遵循了这一约束
2.3 Date 对象提供了一系列 get* 方法,用来获取实例对象某个方面的值
实例方法get类
getTime():返回实例距离1970年1月1日00:00:00的毫秒数
getDate():返回实例对象对应每个月的几号(从1开始)
getDay():返回星期几,星期日为0,星期一为1,以此类推
getYear():返回距离1900的年数
getFullYear():返回四位的年份
getMonth():返回月份(0表示1月,11表示12月)
getHours():返回小时(0-23)
getMilliseconds():返回毫秒(0-999)
getMinutes():返回分钟(0-59)
getSeconds():返回秒(0-59)
例题:
1.
var d = new Date('January 6, 2022');
d.getDate() // 6
d.getMonth() // 0
d.getYear() // 122
d.getFullYear() // 2022
2. 编写函数获得本年度剩余天数
function leftDays() {
var today = new Date();
var endYear = new Date(today.getFullYear(), 11, 31, 23, 59, 59, 999);
var msPerDay = 24 * 60 * 60 * 1000;
return Math.round((endYear.getTime() - today.getTime()) / msPerDay);
}
3.下列代码计算本年度剩余天数
function leftDays() {
var today = new Date();
var endYear = new Date(today.getFullYear(), 11, 31, 23, 59, 59, 999);
var msPerDay = 24 * 60 * 60 * 1000;
return Math.round((endYear.getTime() - today.getTime()) / msPerDay);
}
js对象的Math对象和时间戳对象
最新推荐文章于 2024-09-30 15:23:15 发布