JavaScript

1.初级

1.1 JS的使用方法

1
2
3
4
5
6
7
8
//第一种:写在head标签里
//不推荐头部使用:根据代码运行是自上而下解释的特性,会先解析head标签里JS,然后才解析元素,故需要监听
//需添加 window.onload
<script>
window.onload = function(){
alert(123);// 弹出框,默认设置不可修改
}
</script>
1
2
3
4
//第二种:写在body结束标签上面
<script>
alert(123);
</script>
1
2
3
4
5
6
7
8
9
//第三种:外部导入JS文件
//写在body结束标签上面的内容
<script src="demo.js">
//注意:在引入js文件的script里面,一定不能写js代码
//可以另起一行,按照法二在标签内写js代码
</script>

//写在.js文件中的内容
alert(123);

栗子:

1
2
3
4
5
6
7
8
9
<body>
<p>Hello world!</p>

<script src="demo.js"></script>
<script>
console.log(123);
// 在前端控制台console打印出123
</script>
</body>

1.2 JS获取元素的方法

在js中想要操作元素,或者说执行一些行为,首先需要获取到对应的元素。才能进行下一步的操作,所以要首先学会如何获取元素

1
2
3
4
//JS获取独有标签
document.title 获取标题
document.head 获取头部信息
document.body 获取body内容
1
2
3
4
5
6
7
8
//其他标签的获取
通过id获取元素:document.getElementById("idname");
通过class获取元素:document.getElementsByClassName("classname");
通过标签名获取元素:document.getElementsByTagName("tagdem");
表单中的name:document.getElementsByName("name");
selector选择器(不兼容IE7及以下):
document.querySelector (""); 通过CSS选择器获取一个
document.querySelectorAll(""); 通过CSS选择器获取所有

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS获取元素的方法</title>
<style>
#p1{}
.p2{}
</style>
</head>

<body>
<p id="p1" class="p2">我是段落标签1</p>
<p class="p2">我是段落标签2</p>
<p name="p3">我是段落标签3</p>

<script>
//1.通过id获取元素
var oP = document.getElementById("p1")
//var/let 定义一个变量,通过变量接收获取的元素(注意:变量名不能使用关键字和变量名)
console.log(oP);

//2.通过class获取元素
//当不唯一的时候,需要使用下标,下表从0开始
//法一:下标在document.getElementsByClassName("p2")后面
var oP = document.getElementsByClassName("p2")[1];
console.log(oP);
//法二:下标在oP后面
var oP = document.getElementsByClassName("p2");
console.log(oP[1]);

//3.通过标签名获取元素
var oP = document.getElementsByTagName("p");
console.log(oP[2]);

//4.表单中的name
var oP = document.getElementsByName("p3");
// name属性值不是唯一的 类数组
console.log(oP[0]);

//5.selector选择器
//法一:通过选择器获取单个
var oP = document.querySelector("#p1");
var oP = document.querySelector(".p2");
console.log(oP[0]);//下标使用失败:只能获取选择器选择的第一个元素,谁在最前面就获取谁,加下标没有用
//法二:通过选择器获取多个
var oP = document.querySelectorAll(".p2");
console.log(oP[1]);

//只有id和获取单个选择器不需要加下标,其他都要加下标才显示一个否则是一个集合
// 不支持伪类和伪元素选择器
// “=”是赋值的意思,通常要用赋值的形式

</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//获取嵌套元素
<body>
<p id="p1" CLASS="p2">我是段落标签4
<span>111111</span>
</p>
<script>
//id 只能使用document.getElementById("p1")获取元素,其他可以更换开头(document,id),但不能是集合(嵌套元素)
//获取嵌套在p标签中的span标签
var oP = document.getElementById("p1");
//获取元素,只要保证它是一个确定的标签即可,例:
var oP1 = oP.getElementsByTagName("span");
console.log(oP1[0]);

</script>

1.3 JS的基本事件

事件含义:所谓事件,是指JavaScript捕获到用户的操作,并做出正确的响应

使用:在事件函数里而,有一个关键字this,代表当前发事件的这个元素。事件通过函数完成,在函数内部书写自己想要实现的效果

1
2
3
4
5
//鼠标事件
左键单击 onclick
左键双击 ondblclick
鼠标移入 onmouseover/onmouseenter
鼠标移出 onmouseout/onmouseleave

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS基本事件</title>
<style>
div{
width: 200px;
height: 200px;
border: 1px solid red;
}
</style>
</head>
<body>
<p id="p1" CLASS="p2">我是段落标签1</p>
<p class="p2">我是段落标签2</p>
<p name="p3">我是段落标签3</p>
<div>
111
</div>

<script>
var oP = document.getElementById("p1");
//鼠标单击事件
oP.onclick = function() {
// oP.innerText = "<h1>我不是段落标签1</h1>";
//可以带标签进行渲染这个标签,上面只显示文本不会渲染
oP.innerHTML = '<h1>我不是段落标签1</h1>'
}
//鼠标(连续)双击事件
oP.ondblclick = function (){
oP.innerHTML = '<h1>我不是段落标签1</h1>'
}
//鼠标滑入滑出事件
var oP1 = document.getElementsByTagName("div")[0];
oP1.onmouseenter = function(){
oP1.innerText = "byebye";
}
oP1.onmouseleave = function ()
{
oP1.innerText = "hello";
}

//在修改别的标签时,得使用innerHTML(会解析标签),innerText(不会解析标签)

</script>
</body>
</html>

1.4 JS修改样式

js可以修改规范和不规范的标签的样式,也可以配合点击事件等一起使用

1
2
.style.height 单个样式修改
.style.cssText 多个样式修改

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS修改样式</title>
<style>
div{
width: 200px;
height: 200px;
border: 1px solid red;
background-color: #3A87CD;
}
</style>
</head>
<body>
<div>
111
</div>
<script>
var obox = document.querySelector("div");
//元素获取值 var obox = document.querySelector("div").value;
obox.onclick = function ()
{
obox.style.width = "100px";
//.是不能.一个变量可以使用 obox.style["width"]="20px"
//style[] 可以是一个变量也可以是一个字符串
obox.style.height = "100px";
obox.style.background = "red";

//可以使用cssText修改多个
//obox.style.csstext = "width: 100px; height: 100px;"
}

//一般情况下不这么做(JS和CSS混合在一起),因为一般css很多
//Question: 如何将JS和CSS分开呢?

</script>
</body>
</html>

1.5 JS操作标签属性

1
2
3
4
5
6
7
8
规范的标签属性: . 符号直接操作(可读可写)
.id 修改id
.className 修改class
不规范(自定义)的标签属性:
获取: .getAttribute()
设置: .setAttribute() (增/添)
移除: .removeAttribute() (删)
判断: .hasAttribute()

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS操作标签属性</title>
<style>
div{
width: 200px;
height: 200px;
border: 1px solid red;
background-color: #3A87CD;
}
</style>
</head>
<body>
<div id="box1"></div>
<!--对于页面当中这些属性是可读并且可写的操作-->
<script>
// 标签属性的可写(可赋值、修改值)可读(可以打印出来)-> .操作
var obox = document.querySelector("div");
console.log(obox.id); //undefined
obox.id = "box1";
console.log(obox.id); //box1

//添加一个class属性,并且class的属性值为box1
obox.className = "box2";//增:有则增,无则改
obox.className = "box3";//不是再加一个,是修改操作
//className只操作合法属性
//合法属性:非自定义,页面标签原本已有的属性名
console.log(obox.className);//查
obox.removeAttribute("class");//删

//自定义属性的增删改查
obox.setAttribute("abc","abc1");//增
obox.setAttribute("class","abc1");
obox.setAttribute("abc","abc2");//改:无则增,有则改
console.log(obox.hasAttribute("class"));//查:存在true不存在false
obox.removeAttribute("class");//删

//合法属性也可以通过自定义属性方式添加

</script>
</body>
</html>

1.6 JS与CSS分离

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS与CSS分离</title>
<style>
div{
width: 200px;
height: 200px;
border: 1px solid red;
background-color: #3A87CD;
}
.box1{
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div></div>
<script>
var obox = document.querySelector("div");
obox.onclick = function()
{
//增/改选择器的两种方法
// obox.className = "box1";
obox.setAttribute("class","box1");
}

</script>
</body>
</html>

1.7 JS的基本数据类型

1
2
3
4
5
6
7
8
9
number 数字
string 字符串
boolean 布尔型
undefined 未定义
null 空(对象)
object 对象
前五个是简单数据类型,最后一个是复杂数据类型

typeof x 显示数据类型

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS基本数据类型</title>
</head>
<body>
<script>
//这些类型都是关键字
//number 数字
var a = 123;
console.log(typeof a);
//string 字符串
var b = "123";
console.log(typeof b);
//boolean 布尔型
var c = true;
console.log(typeof c);
//undefined 未定义
var d;
console.log(typeof d);
//null 空(对象)-> 是属于六大基本数据类型之一,只是在显示的时候将其归为object显示
var e = null;
console.log(typeof e);
//object 对象 (数组(列表),函数 ->复杂数据类型)
var f = [1,2,3,4,5];
console.log(typeof f);
</script>
</body>
</html>

2.提升

2.1 JS运算符

算术运算符

  • 算术运算符(基础数字运算) + - * / %
  • 当不是数字之间的运算的时候,+号两边一旦有字符串(引号引起的部分),那么+号就不再是数学运算了,而是拼接,最终结果是字符串。
  • -/*% 尽量将字符串转换成数字(隐式类型转换)
  • NaN: Not a Number number

赋值运算符

  • += -= = /= = 这些是基本的赋值运算符,除此之外还有*++ --**,这两个都存在隐式类型转换,会全部转成数字。

逻辑运算符

  • JS中的逻辑运算用:&&、||、! 来表示。
  • && 和 || 不会进行类型转换,!则会进行类型转换,将后面的数据先转换为布尔型在取反

比较运算符

  • < != >= <= == ===
  • 如果等号两边是boolean、string、number三者中任意两者进行比较时,优先转换为数字进行比较。
  • 如果等号两边出现了null或undefined,null和undefined除了和自己相等,就彼此相等
  • NaN==NaN 返回false,NaN和所有值包括自己都不相等。

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS运算符</title>
</head>
<body>
<script>
//算术运算符
document.write(1 + '2' + "<br/>");//'12' +为字符拼接
document.write(1 - '2' + "<br/>");//-1 隐式转换为number型(- % * /)
document.write(1 + true + "<br/>");//2 true=1,false=0
document.write(1 + null + "<br/>");//1 null=0
document.write(1 + undefined + "<br/>");//NAN: not a Number number

//赋值运算符
var a = 1;
var b = null;
document.write(a++ +"<br/>");//1
document.write(a +"<br/>");//2
document.write(++a +"<br/>");//3
document.write(++b +"<br/>");//隐式转换 null->number = 0

//比较运算符
document.write(('2' == 2) + "<br/>");//true ==在JS中是等于但为不全等(只判断值是否相等,不判断类型)
document.write(('2' === 2) + "<br/>");//false === 全等,先去判断类型是否一致再去判断值是否相等

//逻辑运算符
document.write((2>3&&2<5) + "<br/>");//false &&与
document.write((2>3||2<5) + "<br/>");//true ||或
document.write(!(2>3&&2<5) + "<br/>");//true !非

//隐式转换:-/*% ++ -- (其他类型转number), !(转为布尔型取反)

</script>
</body>
</html>

2.2 JS流程控制

JS中流程控制是if判断和switch选择

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS流程控制</title>
</head>
<body>
<script>
//if判断
var food = "山竹";
if(food == "dinner")
{
document.write("真饱!");
}
else if(food == "山竹"){
document.write("我吃了,但没吃饱!");
}
else{
document.write("好饿!");
}
//简化写法
var a = 1;
a>1?console.log(a+1):console.log(a+3);//表达式?为真的值:为假的值;

//switch选择
var day = 1;
switch(day){
case 1:
document.write("今天星期一");
break;//如果不加break;会一直运行到有break的地方,或default结束
case 2:
document.write("今天星期二");
break;
case 3:
document.write("今天星期三");
break;
case 4:
document.write("今天星期四");
break;
case 5:
document.write("今天星期五");
break;
case 6:
document.write("今天星期六");
break;
case 7:
document.write("今天星期日");
break;
}

var sex = "girl";
switch(sex){
case "girl":
document.write("她是女孩。");
break;
case "boy":
document.write("他是男孩。");
break;
default:
document.write("写错啦!");
}

//break 关键字

</script>
</body>
</html>

2.3 JS循环

for循环

  • for(initialize; test; increment){ statment }

  • JS中的for循环相当于while的简写,更加方便

while循环

  • while (expression){ statement }
  • while是一个基本的循环语句,expression为真的时候,就会执行循环体

do…while循环

  • do…while和while类似,只是会先执行一个循环

for in语句

  • JS中的for也支持类似于python中的用法,可以遍历对象所有的属性。

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS循环</title>
</head>
<body>
<script>
//for循环(先判断再执行)
//声明循环变量,判断循环条件,更新循环变量
for(var i=1; i<=10; i++){
document.write("我是" + i + "号<br/>");
}

for(var i=1;i<=10;i++)
{
if(i==6){
continue;//跳出本次循环,继续下次循环
}
document.write("我是" + i + "号<br/>");
}

//while循环(先判断再执行)
var i = 1;
while(i<=5){
document.write(i + "<br/>");
i++;
}

//do...while循环(先执行再判断)
var i = 1;
do{
document.write(i + "<br/>");
i++;
}while(i<1);

//for in 语句
var array = [1,2,3,4,5];//数组即Python中的列表
for(var i in array){
document.write(i + " ",array[i] + "<br/>")//i接收的对应元素的下标
}
</script>
</body>
</html>

2.4 JS字符串方法

length 长度;slice 切片;substring 截取

indexOf 索引;split 分割;replace 替换

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS字符串方法</title>
</head>
<body>
<script>
var str = "hello world!"
//str[0] = 'a'; //同样字符串不可更改
console.log(str.length);//长度
console.log(str.slice(1, 4));//切片,从下标1切到下标4 [1,4)
console.log(str.substring(1, 4));//截取,从下标1切到下标4 [1,4)
//切片不会自动比较参数的大小,截取会比较参数的大小,都是左闭右开
//str.slice(4, 1)/str.substring(4, 1)
console.log(Object.key(str));//查看对象的方法
</script>
</body>
</html>

2.5 数组方法

length 长度;push 追加;unshift 添加

pop,shift 删除;indexOf 查找

改:slice 切片, join 拼接, sort 正向排序, reverse 反向无排序

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数组方法</title>
</head>
<body>
<script>
var array = ["橘子","苹果","香蕉","栗子"];
array[1] = "葡萄";
console.log(array.length);//长度
console.log(array.slice(1, 3));//切片,左闭右开

var arr = ['a','c','b','g','d'];
console.log(arr.reverse());//反向,无排序
// console.log(arr.sort());//正向排序
console.log(array.join('-'));//拼接

</script>
</body>
</html>

2.6 JS循环练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
<li>111</li>
<li>222</li>
<li>333</li>
<li>444</li>
</ul>
<script>
var oli = document.querySelectorAll("ul li");//获取元素 4个li
// console.log(oli);
//从Nodelist类数组中取出4个li元素
for(var i=0; i<oli.length;i++){
oli[i].onclick = function (){//点击对应的元素弹出对应的文本内容
//alert(this.innerText);//获取元素自身的文本内容

alert(i);//获取下标但全都变成4 -> 作用域问题
//JS里面for循环是没有块级作用域概念,即局部作用域/局部变量
//因为没有此概念,因此它是一个全局变量的i
//全局变量的i,当循环的时候for循环执行到另外一个事件的时候,循环里面正常
// 获取i的值,当循环进到事件里面之后此地方的i是for循环第一个不符合条件的值4
}
}
</script>
</body>
</html>

解决alert(i);的办法:

  • 解决办法1: var定义的全局变量i 换成局部变量 let
  • 解决办法2:利用index_num存储下标值
1
2
3
4
5
6
7
8
9
10
<script>
var oli = document.querySelectorAll("ul li");//获取元素 4个li

//解决办法1: var定义的全局变量i 换成局部变量 let
for(let i=0; i<oli.length;i++){
oli[i].onclick = function (){//点击对应的元素弹出对应的文本内容
alert(i);//获取下标
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
<script>
var oli = document.querySelectorAll("ul li");//获取元素 4个li

for(var i=0; i<oli.length;i++){
// 解决办法2:利用index_num存储下标值
oli[i].index_num = i;

oli[i].onclick = function (){//点击对应的元素弹出对应的文本内容
alert(this.index_num);//读取的是循环里面提前存的0,1,2,3,不是事件存的
}
}
</script>

3.进阶

3.1 JS的内置对象

JS内部已经内置了不少对象,类似于Python中的内置模块,可以直接使用,并且对象一般不需要导入,可以直接使用。

  • Math对象是一个处理数学相关的对象,可以用来执行在数学相关的内容
1
2
3
4
5
6
7
8
9
10
Math.sqrt(4)//开方
Math.abs(-7)//绝对值
Math.PI//π
Math.pow(2, 2)//幂运算 x^y
Math.round(3.6)//取整 4 四舍五入
Math.ceil(3.4)//向上取整 4
Math.floor(3.6)//向下取整 3
Math.max(3, 1, 7, 9)//求最大值
Math.min(2, 1, 5, 6)//求最小值
Math.random()//随机数:默认[0-1]
1
2
3
4
//自定义随机数范围
console.log(Math.random());//随机数:默认[0-1]
console.log(Math.random()*100);//[0,100]
console.log(Math.round(Math.random()*100));//取[0,100]整数
  • 日期对象也是常用对象之一,基本和常用的方法都是需要了解和熟悉
1
2
3
4
5
6
7
8
9
10
11
12
13
//定义一个日期对象
var today = new Date();//本机电脑的时间,不是网络时间

var year = today.getFullYear();//获取年
var month = today.getMonth();//获取月:国外月份从零开始
var date = today.getDate();//获取日
var day = today.getDay();//获取星期
var hour = today.getHours();//获取小时
var min = today.getMinutes();//获取分钟
var sec = today.getSeconds();//获取秒

//变量合并
document.write("现在是北京时间:"+year+"年"+month+"月"+date+"日"+hour+":"+min+":"+sec+"<br/>")
1
2
3
4
5
6
7
8
9
10
//时间戳 
//从1970年到现在时间的总秒数,相当于生活中的密码锁
//当你生成一个新的区块的时候,这个时间戳会按照时间的顺序去反复生成一个对应的数据化的密码。
//如果有黑客想要攻击网站或软件时候,不仅仅需要获取对应这个区块的系统资料还需要破解每一个时间戳所生成的记录
//时间戳用来记录数据的一些关键的时间点,保障数据的一些安全性
//时间戳:1000ms = 1s

var timestan = Date.now();//获取时间戳
document.write(timestan);//ms为单位
//可以网上进行转换

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS的内置对象</title>
</head>
<body>
<script>
//数学对象
console.log(Math.sqrt(4));//开方
console.log(Math.abs(-7));//绝对值
console.log(Math.PI);//π
console.log(Math.pow(2, 2));//幂运算 x^y
console.log(Math.round(3.6));//取整 4 四舍五入
console.log(Math.ceil(3.4));//向上取整 4
console.log(Math.floor(3.6));//向下取整 3
console.log(Math.max(3, 1, 7, 9));//求最大值
console.log(Math.min(2, 1, 5, 6));//求最小值
console.log(Math.random());//随机数:默认[0-1]
console.log(Math.random()*100);//[0,100]
console.log(Math.round(Math.random()*100));//取[0,100]整数

//日期对象
//定义一个日期对象
var today = new Date();//本机电脑的时间,不是网络时间
console.log(today);
var year = today.getFullYear();
console.log(year);
var month = today.getMonth();
console.log(month);//国外月份从零开始
var month = today.getMonth()+1;
console.log(month);
var day = today.getDay();//获取星期
console.log(day);
var date = today.getDate();//获取日
console.log(date);
var hour = today.getHours();
console.log(hour);
var min = today.getMinutes();
console.log(min);
var sec = today.getSeconds();
console.log(sec);

//变量合并
document.write("现在是北京时间:"+year+"年"+month+"月"+date+"日"+hour+":"+min+":"+sec+"<br/>")

//时间戳 从1970年到现在时间的总秒数,相当于生活中的密码锁
//当你生成一个新的区块的时候,这个时间戳会按照时间的顺序去反复生成一个对应的数据化的密码。
//如果有黑客想要攻击网站或软件时候,不仅仅需要获取对应这个区块的系统资料还需要破解每一个时间戳所生成的记录
//时间戳用来记录数据的一些关键的时间点,保障数据的一些安全性
//时间戳:1000ms = 1s
var timestan = Date.now();
document.write(timestan);//ms为单位
//可以网上进行转换
</script>
</body>
</html>

3.2 JS的Window对象

Window对象是所有客户端JS特性和API的主要接入点。它表示Web浏览器的一个窗口或窗体,并且可以用标识符window来引用它。

Window对象定义了一些属性和方法,比如:alert()方法、非常重要的document属性

计时器就是Window中的一个方法,可以用来实现计时的一些操作。

  • 定时器的使用
1
2
3
4
5
6
7
8
9
10
//创建定时器
//setTimeout在指定的时间后仅执行一次
setTimeout(function (){
console.log(123);
},1000);//毫秒为单位

//setInterval以指定时间为周期循环执行
setInterval(function (){
console.log(321);
},1000);
1
2
3
4
5
6
7
8
9
10
11
//清除定时器
//先通过一个变量接收
var timer1 = setTimeout(function (){
console.log(123);
},1000);
clearTimeout(timer1);

var timer2 = setInterval(function (){
console.log(321);
},1000);
clearInterval(timer2);

定时器可以实现定时操作,并且通过window对象来实现跳转操作

  • windows的使用
1
2
3
4
5
6
7
//打开一个新窗口
var w = window.open();//创建一个空白窗口
var w = window.open("demo.html","haha","width=300,height=200");//第三个参数非标准,html5规范也主张浏览器忽略它

w.alert("hello!");//弹出框
w.location = "https://www.bilibili.com/";//跳转新页面的传统方式
w.close();//关闭窗口

3.3 JS的函数

JS 的函数包裹在花括号当中,使用关键词function来定义。函数可以挂载在一个对象上,作为一个对象的属性,称为对象的方法。

  • JS函数特性:在JS中,函数即对象,程序可以随意操控它们。比如,JS可以把函数赋值给变量,或者作为参数传递给其他的函数,甚至可以设置属性,调用它们的方法。

JS有名函数和匿名函数

  • 有名函数:有名字的函数,使用时是:函数名加上括号执行,充当时间函数执行

  • 匿名函数:没有名字的函数,匿名函数不能单独出现,一般充当事件函数,比如点击事件调用的函数

1
2
3
4
5
6
7
8
9
10
//有名函数
function func(){
console.log(1);//打印一个1
}
func();//函数调用

//匿名函数
document.onclick = function (){
console.log(2);//事件触发调用
}

函数的参数/传参

  • 形参,实参,不定参数
1
2
3
4
5
6
7
8
9
10
//x为形参(形式参数),3为实参(实际参数)
function func(x){
console.log(x);
}
func(3);

function sum(x,y){
console.log(x + y);
}
sum(1,7);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//不定参数(不定长参数)
function add(x,y){
console.log(x, y);
console.log(arguments);//不定长参数:统一获取,有多少拿多少
}
add(1);
add(2,3);
add(1,2,3);
//add(1); 1 undefined

//获取不定长参数arguments中的值
function add1(){
// console.log(arguments);
for(var i=0; i<arguments.length;i++) {
console.log(arguments[i]);//数组值
}
for(var i in arguments){
document.write(i);//索引值
}
}
add1(1,3,5,7,9);

函数的分类

  • 功能性函数,返回性函数
1
2
3
4
5
6
7
//功能性函数
//无返回值,得到的结果为undefined
// alert(1);
var a = alert(1);//定义一个变量无值传入
console.log(a);//undefined
var b = console.log(2);
console.log(b);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//返回性函数
//有返回值,所以会返回结果
var oBox = document.querySelector("div");
console.log(oBox);//<div></div>

//自定义一个函数
function func1(){
console.log(8);
}
var a = func1();//8
console.log(a);//undefined
function func2(){
console.log(1);
return "我返回了";
}
var a = func2();//1
console.log(a);//我返回了

//return返回后的函数不会执行
function func3(){
console.log(7);
return "我返回了";
console.log(3);
}
var a = func3();//7
console.log(a);//我返回了

函数的作用域

  • 全局作用域,函数作用域,块级作用域
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//在函数内部不使用var声明的变量都会成为全局变量
//在函数内部使用var声明的变量是局部变量

var a = 100;
function func() {
var a = 200;
alert(a);
}
alert(a);//100
func();//200
alert(a);//100

var a = 100;
function func() {
// var a = 200;
a = 200;
alert(a);
}
alert(a);//100
func();//200
alert(a);//200

var a = 100;
function func1() {
var a = 200;
function func2() {
var a = 300;
}
func2();
alert(a);
}
alert(a);//100
func1();//200
alert(a);//100

var a = 100;
function func1() {
var a = 200;
function func2() {
a = 300;
//子作用域只能改变父作用域的值,不能向上改变
}
func2();
alert(a);
}
alert(a);//100
func1();//300
alert(a);//100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//推荐用let,块级作用域的变量

{
var i = 1;
}
console.log(i);

{
//块级作用域/局部作用域
//只在花括号内部有效
let j = 2;
console.log(j);
}
// console.log(j);报错

自定义函数

  • ~ + - !()
1
2
3
4
5
6
7
8
9
~function (){
console.log(1);
}();
+function (){
console.log(1);
}();
-function (){
console.log(1);
}();

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS函数</title>
</head>
<body>
<div></div>
<script>
var oBox = document.getElementsByTagName("div");
function func(){
alert(1);
};
oBox.onclick = func;//当作点击事件时,不能加上括号
</script>
</body>
</html>

3.4 JS异常

写代码会出现或多或少的错误,而出现错误就会终止代码的运行;能不能在可能出现错误的代码它不出现错误或执行自己写的错误
提供一些异常处理机制,具有一部分异常恢复能力

1
2
3
4
5
6
7
8
9
try{
//先执行这里,没有问题的话就会执行完成
}catch(e){
//如果输入不合法,将执行这里的逻辑
alert(e);//告诉用户产生了什么错误
throw new Error("太胖了!");//或者自定义错误
}finally{
//不管是否抛出异常,都会执行
}

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS异常</title>
</head>
<body>
<button id="btn" onclick="func()">点我</button>
<script>
//正确代码:
// function func() {
// var num = 123;
// alert("我是"+num);
// }

function func() {
//var num = 123;
try{
alert("我是"+num);
}catch(e){
alert("错误类型:"+e.name+" 错误信息:"+e.message);
}finally {
alert("我已经执行完毕");
}
}

//捕获异常
function func() {
var num = 123;
try{
if(num<100)throw "太小了";
if(num==100)throw "刚昂好";
if(num>100)throw "太大了";
//e接受throw里的信息
}catch(e){
alert(e);
}finally {
alert("我已经执行完毕");
}
}
</script>
</body>
</html>

4.练习