珠峰培训之js中的Math函数 Date函数详解
2016-07-31 23:15:00
231
1.Math函数
1.1 Math方法
Math.abs();取绝对值
Math.ceil();向上取整
Math.floor();向下取整
Math.round();四舍五入 在负数情况下五及五以下是舍
Math.max(val1,val2,val3…);求最大值
Math.min(val1,val2,val3…);求最小值
Math.abs(-12);
Math.ceil(12.5);
Math.floor(12.5);
Math.round(12.4);
Math.min(11,12,13,14,15);
Math.max(11,12,13,14,15);
1.2 随机数
Math.random(); 获取[0,1)之间的随机小数(包含0不包含1)
获取[m,n]之间的随机整数
Math.round(Math.random()*(n-m)+m); //公式
2.Date函数
2.1 获取时间
- 获取电脑时间
var time = new Date(); //获取当前电脑时间
var year = time.getFullYear();
var month = time.getMonth()+1; // 获得0-11
var day = time.getDate();
var week = time.getDay(); //0-6之间,代表周日到周六
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var msecond = time.getMilliseconds();
- 获取目标时间,在Date()中传参数
var targetTime = new Date("2016-06-20 21:00:00");
Date()支持十多种传入时间格式,在日期中用”-“可以连接时间,但是在IE6/7/8中不兼容,需要改成”/”
var targetTime = new Date("2016/06/20 21:00:00");
2.2 计算倒计时
getTime(); 获取当前时间距离1970年1月1日午夜(00:00)到现在的毫秒差
则用目标时间距离1970年的毫秒差 减去 当前时间距离1970年的毫秒差,则是目标时间与当前时间之间的差值
3.定时器
- window.setInterval([function],[interval]); 每隔一段时间执行一次
- window.setTimeout([function],[interval]); 隔一段时间仅执行一次
- clearInterval(); clearTimeout(); 清除定时器
- 定时器的返回值是一个数字,代表这是第几个定时器
var interval = 10,n=0;
var timer = window.setInterval(function(){
n++;
if(n > 10){
window.clearInterval(timer);
}
},interval);