Math
Math object is not a constructor, just use it directly.
<script>
//1 Math.PI
console.log(Math.PI); //3.141592653589793
//2 Math.max()
console.log(Math.max(3, 1, 8)); //8
console.log(Math.max(3, -9, 7)); //7
console.log(Math.max('45', 8, 0)); //45 这里有隐式转换
console.log(Math.max('hhh', 8, 0)); //NaN
console.log(Math.max()); //-Infinity
//3 Math.abs()
console.log(Math.abs(1)); //1
console.log(Math.abs(-1)); //1
console.log(Math.abs('1')); //1 这里有隐式转换
console.log(Math.abs('aaa')); //NaN
//4 Math.floor() 向下取整
console.log(Math.floor(1.1)); //1
console.log(Math.floor(1.9)); //1
//5 Math.ceil() 向上取整
console.log(Math.ceil(1.1)); //2
console.log(Math.ceil(1.9)); //2
//6 Math.round() 四舍五入 .5特殊,是往大数取
console.log(Math.round(1.3)); //1
console.log(Math.round(1.8)); //2
console.log(Math.round(1.5)); //2
console.log(Math.round(-1.3)); //-1
console.log(Math.round(-1.5)); //-1
//7 Math.random() 产生随机数,范围[0,1)
//8 产生两个数之间的随机数(包含两个数)
console.log('-------');
console.log(getRandom(0, 9)); //范围[0,9]
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
Date
Date is a constructor and must be instantiated
var now = new Date();
console.log(now); //返回当前时间
var myTime = new Date('2021-10-10');
console.log(myTime);//返回指定日期
Get the total number of milliseconds (time stamp): the number of milliseconds since January 1, 1970 (Coordinated Universal Time).
<script>
// 实例化Date对象
var now = new Date();
//1用于获取对象的原始值
console.log(now.valueOf());
console.log(now.getTime());
// 2. 简单写可以这么做(!!!!推荐)
var now = +new Date();
// 3. HTML5中提供的方法,有兼容性问题
var now = Date.now();
</script>
Case: Countdown Realization
Analysis: The input time minus the current time is the remaining time, which is realized by using the timestamp, and then the timestamp is converted into hours, minutes and seconds
<script>
function countDown(time) {
var nowTime = +new Date(); // 返回的是当前时间总的毫秒数
var inputTime = +new Date(time); // 返回的是用户输入时间总的毫秒数
var times = (inputTime - nowTime) / 1000; // times是剩余时间总的秒数
//1s=1000ms
var d = parseInt(times / 60 / 60 / 24); // 天
d = d < 10 ? '0' + d : d;
var h = parseInt(times / 60 / 60 % 24); //时
h = h < 10 ? '0' + h : h;
var m = parseInt(times / 60 % 60); // 分
m = m < 10 ? '0' + m : m;
var s = parseInt(times % 60); // 当前的秒
s = s < 10 ? '0' + s : s;
return d + '天' + h + '时' + m + '分' + s + '秒';
}
console.log(countDown('2021-1-24 00:00:00'));
var date = new Date();
console.log(date); //打印当前时间
</script>
result: