JavaScript-03

Math方法

  • sqrt:开方
  • abs:绝对值
  • PI:π
  • pow(x,y) :x的y次方
  • round:取整(四舍五入)
  • random:随机数0~1
  • min(x,y,z):从x,y,z中取最小值
  • max(x,y,z):从x,y,z中取最大值
  • ceil:向上取整
  • floor:向下取整

例:

1
Math.round(Math.random*100) //随机生成1~100的随机数

日期对象

Date方法

new Date():新建日期对象

  • getFullYear:获取年份

  • getMonth:获取月份

  • getDay:获取日

  • getHours:获取时

  • getMinutes:获取分

  • getSeconds:获取秒

例:

1
2
3
4
5
6
7
8
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth()+1;
var day = today.getDay();
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
console.log(year+'年'+month+'月'+day+'日'+hour+':'+minute+':'+second);

时间戳

时间戳:格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

1
2
3
var timestamp = Date.new();//新建

console.log("timestamp:"timestamp);

函数

函数的定义

函数是通常是把一系列重复使用的操作封装成一个方法,方便调用

函数分类:有名函数,匿名函数

定义有名函数:

1
2
3
4
function 函数名(){
//代码块
console.log("OK")
}

自定义函数:

1
2
3
var result=function 函数名(){
//代码块
}

调用函数

1
函数名();

匿名函数:

​ 匿名函数一般充当事件函数

例:

1
2
3
4
5
6
7
var box = document.getElementById('box');

box.onclick = function(){

console.log(123);

};

自调用函数:

自调用函数是在函数表达式写完后自动执行

其函数表达式前面加上 (,),+,-,!,~

例:

1
2
3
4
5
6
7
(function(){
console.log("ok");
})();

+function(){
console.log("ok");
}();

函数参数:

1
2
3
4
5
function sum(){
var a = x+y+z; //需要传入3个参数x,y,z
console.log(argments); //argments为接收的不定参数
console.log(a)
}

定时器

  • setTimeout:设置定时器

  • clearTimeout:清除定时器

  • setInterval:设置定时器

  • clearInterval:清除定时器

注:清除定时器的时候,要给定时器加个名字

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var btn = document.getElementsByTagName("button")[0];
//1000毫秒=1秒

setTimeout(function () {

console.log(123)

},1000);

var timer = setInterval(function () {
console.log(123)
},1000);

btn.onclick = function () {
clearInterval(timer);
};

setTimeout与setInterval的区别

setTimeout执行一次,setInterval一直循环执行,直到清除定时器

请我喝杯茶呗~