1、Math.random随机点名操作
// 会得到一个大于等于0 小于1
console.log(Math.random());
// 想得到一个 0到5 的随机数
console.log(Math.floor(Math.random() * (5+1)));
// 2~5 min+Math.floor(Math.random()*(Max - min))不包含5
// 包含5
console.log(2+ Math.floor(Math.random() * (5-2+1)))
// 由于取随机数是一个很常用的方法,所以可以将它封装成一个函数
function arrayRandomValue(array,start=1,end){
end = end? end : array.length;
start--;
const index = start + Math.floor(Math.random() * (end-start))
return array[index];
}
2、日期时间戳的使用与计算脚本执行时间
const date = new Date();
// 返回的是一个对象object类型
console.log(typeof date)
// 返回的是时间戳
console.log(date * 1)
const hd =Date()
// 返回的是字符串string类型
console.log(typeof hd)
// 返回NaN
console.log(hd * 1)
// 获取时间戳的方法
const data = Date.now()
const start = Date.now();
for(let i= 0;i<200000;i++){}
const end = Date.now();
// 通过时间戳来计算这个循环了多长时间
console.log((end-start)/1000 + "秒")
查看这个for循环执行了多长时间,返回的单位是ms
getMonth()这个方法默认从0开始
3、ISO与TIMESTAMP格式互换
const date = new Date("1999-11-22 12:20:10")
// 下面方法都可以将时间转换成时间戳
console.log(date *1)
console.log(Number(date))
console.log(date.valueOf())
console.log(date.getTime())
// 将时间戳转换成日期
const timestamp = date.vauleOf()
console.log(new Date(timestamp))
4.封装日期格式化函数
const date = new Date("1999-11-22 12:20:10")
// 得到日期的年份
console.log(date.getFullYear());
// 得到日期的月份,因为这个方法从零开始所以要加1
console.log(date.getMonth() + 1);
// 得到日期的日
console.log(date.getDate())
// 得到时分秒
console.log(date.getHours())
console.log(date.getMinutes())
console.log(date.getSeconds())
const formDate = `${date.getFullYear()}年${date.getMonth() + 1}月`
function dateFormat(date,format = "YYYY-MM-DD HH:mm:ss"){
const config={
YYYY:date.getFullYear();
MM:date.getMonth() + 1;
DD:date.getDate();
HH:date.getHours();
mm:date.getMinutes();
ss:date.getSeconds();
};
for(const key in config){
// repalce 字符串替换
format = format.repalce(key,config[key])
}
return format
}