学习内容:
学习内容:
(一)Math对象
一、Math对象
1.取绝对值 Math.abs( )
Eg: var n=Math.abs(-9)
2.返回x和y次幂 Math.pow( )
Eg: var n=Math.pow(3,3)
3.返回某数的平方根 Math.sqrt(x)
Eg: var n=Math.sqrt(9)
4.返回几个数组的最大值 Math.max( )
Eg: var n=Math.max(10,9,8,7,6)
5.返回几个数中的最小值 Math.min( )
Eg: var n=Math.min(212,3,4,56,78)
console.log(n);
6.四舍五入 得到的整数 Math.round( )
Eg: var x=Math.round(10,20,5,0,90)
console.log(x);
7.向上取整 Math.ceil( )
Eg: var y=Math.ceil(9.01)
console.log(y);
8.向下取整 Math.floor( )
Eg:var k=Math.floor(9.99)
console.log(k);
9.随机数 Math.random() { [0,1) 取0-1之间的随机数(不包括1) }
Eg: var r=Math.random()
console.log(r);
10.parseInt 取整
Eg: var l=parseInt(2.96)
console.log( l );
二、取俩数之间随机的整数公式:
1. Math.round(Math.random()*(max-min)+min)
2. Math.floor(Math.random()*(max-min+1)+min)
练习1 取0-10之间的随机整数
var r1=Math.round(Math.random()*(10-0))
Math.floor(Math.random()*(10+1))
document.getElementsByTagName('h1')[0].innerHTML=r1
练习2 取10-20之间的随机整数
Math.round(Math.random()*(20-10)+10)
Math.floor(Math.random()*(20-10+1)+10)
三、封装一个函数
取俩个数之间的随机整数
function getRandom(min,max) {
return Math.floor(Math.random()*(max-min+1)+min)
}
(二)定时器
一、callback:回调函数
把函数当作一个参数传到另一个函数中
二、定时器
1.定时器:
setInterval(callback,time) 每隔固定时间代码执行一次
2.移除定时器
clearInterval(定时器)
var time1=setInterval(function(){
console.log("hello 吃羊肉");
// 移除定时器
clearInterval(time1)
},1000);
三、延时器
1.延时器:
setTimeout(callback,time) 延时固定时间执行一次 只执行一次
2.移除定时器:
clearTimeout(定时器)
setTimeout(callback,time) 延时固定时间执行一次 只执行一次
var time2=setTimeout(function(){
alert("hello 我不吃")
// 移除延时器
clearTimeout(time2)
},5000);
(三)时间对象
一、时间事件
1.创建一个日期对象:new.Date()
Eg: new.Date(2021.10.01)
1)不传参 获取的是当前的时间
2)可以传参 字符串:'2022-8-23 00:00:00'
2.获取年份:getFullYear()
3.获取月份:getMonth()
4.获取日期:getDate() 获取周几:getDay()
5.获取小时:getHour()
UTC 获取的是世界时间 0时区的时间 我们在东八区 和0时区差8个小时
6.获取分钟:getMinutes()
7.获取秒数:getSeconds()
8.获取时间戳:getTime()(距离1970.1.1的毫秒数)
9.补充:
所有get方法都有set方法,用于设置时间
UTC为世界时间
Eg: date.getUTCHours( )