Math对象是一个固有对象,提供基本数学函数和常数。Math(算数)对象的作用是:执行常见的算数任务。Math 对象提供多种算数值类型和函数,因此不需要在使用这个对象之前对它进行定义
Math的常用方法
Math.ceil()
console.log(Math.ceil(.95));
输出是1
console.log(Math.ceil(4));
输出是4
Math.floor()
console.log(Math.floor(5.95)
console.log(Math.floor(5.05))
两个都是输出的是5
Math.random()
console.log(Math.random());
输出一个0-1之间的随机小数
console.log(Math.floor(Math.random() * 10 + 1));
Math.round()
console.log(Math.round(0.9));输出: 1
Date对象
Date 对象用于处理日期和时间。=
创建 Date 对象 var sum=new Date()
Date 对象会自动把当前日期和时间保存为其初始值
Date方法:
date.getDate(); 从 Date 对象返回一个月中的某一天
date.getDay() 从 Date 对象返回一周中的某一天
date.getMonth() 从 Date 对象返回月份
date.getFullYear() 从 Date 对象返回年
date.getYear() 请使用 getFullYear() 方法代替
date.getHours() 返回 Date 对象的小时
date.getMinutes() 返回 Date 对象分钟
date.getSeconds() 返回 Date 对象秒数
// 当前日期
var old = new Date();
// 获取发布朋友圈的时间
var old1 = new Date("2000-10-1-10:00");
// 转换成毫秒
old = Date.parse(old);
old1 = Date.parse(old1);
// 计算时间差
var time = old - old1;
// 转换秒
var htime = parseInt(time / 1000);
// 转换分
var ftime = parseInt(time / 1000 / 60);
// 转换小时
var xtime = parseInt(time / 1000 / 60 / 60);
// 转换成天数
var ttime = parseInt(time / 1000 / 60 / 60 / 24);
console.log(htime);
console.log(ftime);
console.log(xtime);
console.log(ttime);
//分支结构判断.根据不用的情况输出不用的结果
if (ttime >= 1) {
console.log(ttime + "天以前");
} else if (xtime > 0 && xtime < 24) {
console.log(xtime + "小时以前");
} else if (ftime > 0 && ftime < 60) {
console.log(ftime + "分以前");
} else if (htime > 0 && htime < 60) {
console.log(htime + "秒以前");
}
定时器函数
// var to = 0;
// var time = setInterval(function() {
// if (to < 5) {
// to++;
// console.log(to);
// } else {
// clearInterval(time);
// }
// }, 1000)
// var to = 6;
// var time = setInterval(function() {
// if (to > 1) {
// to--;
// console.log(to);
// } else {
// clearInterval(time);
// }
// }, 1000)