JavaScript基础

释放双眼,带上耳机,听听看~!

目录

一、JS语法

1、了解JS

2、JS语法规则

3、JS数据类型

4、JS操作符

二、JS流程控制语句

1、JS分支语句:

2、JS循环语句

三、JS函数

四、内置对象

1、JS中的数组

2、JS中的String

3、JS中的Math

4、JS中的Date对象

五、DOM基础

1、DOM查找方法

2、DOM属性设置与获取

六、DOM事件

七、BOM基础

1、window对象

2、定时器

3、location对象

4、history对象


一、JS语法

1、了解JS

JS概念、JS组成、JS使用、JS使用外部文件优势、JS注释、JS分号。

1.1  JS 概念

JS 是一种解释性脚本语言。是一种基于对象和事件驱动的客户端脚本语言,最初的设计是为了检验 HTML 表单输入的正确性。主要用来向 HTML 页面添加交互行为。

1.2  JS 组成

完整的 JS 是由 ECMAScript(核心)、DOM(文档对象模型)、BOM(浏览器对象模型)组成。

1.3  JS 使用

可以在 head 或 body 中使用 <script> 标签嵌入 JS 脚本或引入 JS 脚本。

1.3.1 <script>标签属性有

defer 延迟脚本(页面加载完成之后再加载,按照页面中出现的顺序执行);
async 异步脚本(和页面同时加载,不保证按页面中出现的顺序执行);
……
defer、async 只对外部文件可以使用;

1.3.2 JS 使用外部文件优势:

可维护性、可缓存(多个页面使用同一个文件,只需下载一次,加快了页面的加载速度)、适应未来。

1.4  JS 注释

// 单行注释   /**/多行注释。

1.5 JS 分号

ECMAScript 中的语句以一个分号结尾,如果省略分号,则由解析器确定语句的结尾。

2、JS语法

标识符概念、标识符命名规则;变量概念、变量的声明与赋值、全局变量和局部变量。

ECMAScript 中的一切(变量、函数名、操作符)都区别大小写。

2.1  JS 标识符

2.1.1  标识符概念

指的是变量、函数、属性的名字、或者函数的参数。

2.1.2  标识符命名规则

1)由字母、数字、下划线_、美元符号 $ 组成;

2)不能以数字开头;

3)不能使用关键字、保留字等作为标识符。

2.2  JS 变量

2.2.1  变量概念

变量是松散类型,可以用来保存任何类型的数据;换句话说,每个变量仅仅是一个用于保存值的占位符而已。定义变量使用 var 操作符( var 是一个关键字),后跟变量名(变量名是一个标识符)。

2.2.2  变量声明与赋值

1)
变量声明:使用 var(旧)、let(新)、const(常量) ,语法:var / let / const  变量名 ( var age; )。

2)变量赋值:①声明的时候同时赋值( var 变量名 = 值; )、②先声明后赋值( var 变量名;  变量名 = 值; )。

3)注意:

 
Δ 省略 var 声明的变量是全局变量,即使在函数内声明,函数外使用 var 声明的变量是全局变量。全局变量不推荐使用。


1
2
3
4
5
6
7
1function test(){
2  message = &#x27;hi&#x27;; // 全局变量 不推荐使用
3  return message;
4}
5console.log(test());
6console.log(message);
7

Δ 函数内
使用 var 声明的变量是局部变量,局部变量在函数退出后就会被销毁,它的范围被限制在该变量被申明的函数体内,同名变量在不同的函数体内互不冲突。 


1
2
3
4
5
6
7
1function test(){
2  var message = &#x27;hi&#x27;; // 局部变量
3  return message;
4}
5console.log(test());
6console.log(message); //报错!局部变量在函数外部是访问不了的
7

一次声明多个变量,用逗号隔开。 


1
2
1var name_01=&quot;marry&quot;, age=18, email=&quot;marry@sohu.com&quot;, address, num=null; 
2

3、JS数据类型

6种基本数据类型、1种复杂数据类型;typeof、console.log()、console.table();Undefined、Null、Boolean 隐士类型转换;Number ==>
 NaN、isNaN(n)、parseInt()、parseFloat()、Number函数类型转换;String ==>  多行字符串、模版字符串、操作字符串、string函数类型转换 。

6种基本数据类型:Number 、Boolean、String、Undefined、Null、
Symbol。1种复杂数据类型:Object。

3.1  typeof Δ

1)语法:typeof  变量 / typeof  (变量)。

2)功能:
检测
变量数据类型。

3)
返回值:string 类型,typeof 运算符把类型信息当作字符串返回。typeof 返回值有7种可能 number、boolean、string、undefined、symbol、function、object。
array、null 等特殊对象使用 typeof 一律返回 object,这正是 typeof 的局限性。
检测一个变量是否是数组有3种方式:isArray() 方法、创建自己的 isArray() 函数、instanceof。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1var name = &#x27;小明&#x27;,
2    age = 18,
3    student = true,
4    fellow = [&#x27;小红&#x27;,&#x27;小芳&#x27;],
5    school,
6    teacher = null;
7var fun = function(){
8
9}
10var sym = Symbol();
11
12console.log(typeof (name)) // string
13console.log(typeof (age)) // number
14console.log(typeof (student)) // boolean
15console.log(typeof (fellow)) // object
16console.log(typeof (school)) // undefined
17console.log(typeof (teacher)) // object
18console.log(typeof (fun)) // function
19console.log(typeof (sym)) // Symbol
20

4)在控制台中打印:console.log()、
console.table() 数据以表格的形式显示,后面跟的必须是一个
数组或是一个
对象。table 第一列是 index,数组对应的是索引,对象对应的是属性名。


1
2
3
4
5
6
1console.table([1,2,3,4]);
2console.table({
3    name: &#x27;小明&#x27;,
4    age: 18
5})
6

3.2  Undefined 类型

 Undefined(未定义) 类型只有一个值,即特殊的 undefined。一般而言,不存在需要显式地把一个变量设置为 undefined 值的情况。


1
2
3
4
5
6
7
1var message;
2console.log(message == undefined); // true
3console.log(message === undefined); // true !!!!!!
4
5var message = undefined;
6console.log(message == undefined); // true
7

3.3  Null 类型

null 空对象指针。
如果定义的变量准备在将来用于保存对象,最好将变量初始值设为 null 而不是其他值。

undefined 值派生自 null值 ,所以 undefined == null 返回结果为 true,全等返回 false。


1
2
3
4
5
1null == undefined //true
2null === undefined //false
3null === null //true !!!!!!
4undefined === undefined //true
5

3.4  Number 类型 Δ

Number 表示整数和浮点数。

3.4.1  NaN

NaN 非数值(Not a Number)是一个特殊的数值。

任何涉及 NaN 的操作(例如NaN/10)都会返回 NaN,NaN 与任何值都不想等,包括 NaN 本身,NaN 的数据类型为 Number。

3.4.2  isNaN(n)

1)功能:
检测 n 是否是“非数值”

2)返回值:boolean,只有 false 和 true,true 非数值,false 数值。参数 n 可以是任何类型;

3)说明:isNaN(n) 在接收到一个值之后,会尝试将这个值转换为数值。某些不是数值的值会直接转换为数值。

3.4.3  数值转换

有 3 个函数可以把非数值转换为数值:Number()、parseInt() 和 parseFloat()。Number() 可用于任何数据类型,
parseInt() 和 parseFloat() 专门用于把字符串转换成数值。

1)parseInt()

parseInt():
提取整数,提取的内容必须以数字开头,如果以非数字开头得到的结果都是 NaN。parseInt() 会忽略字符串前面的空格,直到找到第一个非空格字符。

parseInt('')  转换空字符串返回 NaN。parseInt() 提供第二个参数,转换时使用的基数,即多少进制。

2)parseFloat()

parseFloat():
提取浮点数,从第一个字符开始解析每个字符,直至遇见一个无效的浮点数字符为止。
parseFloat() 只提取到第一个小数点,parseFloat() 与 parseInt() 的第二个区别在于始终都会忽略前导的零。

3)Number()

可用于任何数据类型,也可直接做四则运算。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
12 / 0; // Infinity 0不能当分母
20 / 0; // NaN
3
4var str = &#x27;abc123&#x27;;
5var num = parseInt(str);
6if (num == NaN) {
7    alert(NaN);
8}else if(num == 123){
9    alert(123);
10}else if (typeof num == &#x27;number&#x27;) {
11    alert(&#x27;num&#x27;)
12}else{
13    alert(&#x27;str&#x27;);
14}
15
16

3.4.4  类型转换

显示类型转换:手动执行(原始类型转换、对象类型转换):Number( )、String( )、Boolean( );

隐士类型转换:程序自动执行,四则运算、if 语句、Native 语句。

1)Number 函数  原始类型转换

1、数值:转换后还是原来的值。

2、字符串:如果可以被解析为数值,则转换为相应的数值,否则得到 NaN,
空字符串转为 Number 为 0。

3、布尔值:true 转成1,false 转成0。

4、
undefined:转成 NaN。

5、
null:转成 0。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1// 数值转换
2Number(1);  // 1
3
4// 字符串转换
5Number(&#x27;1&#x27;);  // 1
6Number(&#x27;num&#x27;);  // NaN
7
8// 布尔型转换
9Number(true);  // 1
10Number(false);  // 0
11
12// undefined 转换
13Number(undefined); // NaN
14
15// null 转换
16Number(null) // 0
17

2)Number()函数对象类型转换
(对象转换成 Number() 函数)

1、先调用对象自身的 valueOf() 方法,如果该方法返回原始类型的值(数值、字符串、布尔值),则直接对该值使用 Number() 方法,再进行后续步骤。

2、如果 valueOf() 方法返回复合类型的值,再调用对象自身的 toString() 方法,如果 toString() 方法返回原始类型的值,则对该值使用 Number() 方法,不再进行后续步骤。

3、如果 toString() 方法返回的是复合类型的值,则报错。

Number() 函数对象类型转换规律,a是一个对象:

a.valueOf( ) ==》返回的是原始类型的值 ==》Number( )
a.valueOf( ) ==》返回的是复合类型 ==》a.toString( ) ==》返回的是原始类型 ==》Number( )
a.valueOf( ) ==》返回的是复合类型 ==》a.toString( ) ==》返回的是复合类型 ==》报错


1
2
3
4
5
6
7
8
9
10
11
1var a = {a: 1};
2console.log(Number(a)) //NaN
3/*
4  a.valueOf()
5  {a: 1}
6  a.toString()
7  &quot;[object Object]&quot;
8  Number(&quot;[object Object]&quot;)
9  NaN
10*/
11

3.5  String 类型

字符串由单引号 ' ' 、双引号 “ ” 表示,' ' 或 " " 只是一种表示方式,不是字符串的一部分。

1、语法:str.toString()、String(变量)。

2、功能:将 str 转换为字符串。

3、返回值: str 的一个副本。参数 str 是要转换的内容,可以是数值、布尔值、对象和字符串。

4、说明:不知道要转换的值是否是 null 和 undefined 的情况下,可以使用
Srting() 函数,它能够将任何类型的值转换为字符串。

3.5.1  多行字符串

\n 换行。
ES6 标准新增了一种多行字符串的表示方法,用反引号

1
1`

1
1`

 表示。


1
2
3
1var message = `欢迎
2来到js世界`;
3

3.5.2  模版字符串

把多个字符串连接起来,可以用 + 号连接符。如果有很多变量需要连接,用 + 号比较麻烦。
ES6新增了模板字符串,表示方法和多行字符串一样,但是
模版字符串会自动替换字符串中的变量


1
2
3
4
5
6
7
8
9
10
11
12
13
1//+号连接
2var name = &#x27;小明&#x27;;
3var age = 20;
4var message = &#x27;你好, &#x27; + name + &#x27;, 你今年&#x27; + age + &#x27;岁了!&#x27;;
5alert(message);
6
7//模版字符串
8var name = &#x27;小明&#x27;;
9var age = 20;
10var message = `你好, ${name}, 你今年${age}岁了!`;
11alert(message);
12
13

3.5.3  操作字符串

字符串是不可变的,如果对字符串的某个索引赋值,不会错误,也没有任何效果。


1
2
3
4
1var s = &#x27;Test&#x27;;
2s[0] = &#x27;X&#x27;;
3console.log(s); // s仍然为&#x27;Test&#x27;
4

3.5.4  String()函数原始类型转换

1、数值:转为相应的字符串。

2、字符串:转换后还是原来的值。

3、布尔值:true 转为 ”true”,false 转为 ”false”。

4、undefined:转为 ”undefined”。

5、null:转为”null”。

3.5.5  String()函数对象类型转换

1、先调用 toString() 方法,如果 toString() 方法返回的是原始类型的值,则直接对该值使用 String() 方法,下再进行后续步骤。

2、如果 toString() 方法返回的复合类型的值,再调用 valueOf() 方法,如果 valueOf() 方法返回的是原始类型的值,则对该值使用 String() 方法,不再进行后续步骤。

3、如果 valueOf() 方法是复合类型的值,则报错。

String()函数对象类型转换规律,a是一个对象:

a.toString( ) ==》返回的是原始类型 ==》String( )
a.toString( ) ==》返回的是复合类型 ==》a.valueOf( ) ==》返回的是原始类型 ==》String( )
a.toString() ==》返回的是复合类型 ==》a.valueOf( ) ==》返回的是符合类型 ==》报错

3.6  Boolean 类型

Boolean 用于表示真假的类型,true 表示真、真为1,false 表示假、假为0。

3.6.1  隐式类型转换

null、undefined、NaN、''(空字符串) 、0 转 Boolean 值为 false,其它一律为 true。

4、JS操作符

什么是表达式、算数操作符、赋值操作符、比较操作符、三元操作符、逻辑操作符。

4.1  什么是表达式

将同类型的数据(如常量、变量、函数等),用运算符号按一定的规则连接起来,有意义的式子称为表达式。
表达式先计算右侧,得到结果,再赋值给变量。


1
2
3
1var x = 10;
2    x = x+1;  // 11
3

4.2  算数操作符

  • 加、- 减、* 乘、/ 除、% 取余。

1)递增:++a 和 a++ 都是对 a 进行递增的操作。

2)区别:
++a 先返回递增之后 a 的值;a++ 先返回 a 的原值,再返回递增之后 a 的值。

3)递减同理。

4)只要有一个字符串,+ 就起连接符的作用( 5 + “5” = 55 )。


1
2
3
4
5
6
1var num1 = 10, num2 = 5, num3 = num1++ - num2;
2console.log(num3);  // 5
3
4var x1 = 20, x2 = 30, x3 = --x1 + x2--;
5console.log(x3);  // 49
6

4.3  赋值操作符

简单赋值: =;

复合赋值: +=、-=、*=、/=、%=。
复合赋值是算术操作符的缩写形式。


1
2
3
4
5
6
7
1var a = 10;
2var b = 20;
3a += 5;  // a = a+5; 15
4b %= 4;  // b = b%4; 0
5console.log(a);
6console.log(b);
7

4.4  比较操作符

1)>、<、>=、<=、==、===、!=、!==。

     
== 相等(两个等号),会自动转换数据类型再比较
,只比较值是否相等;

   
  === 全等(三个等号),直接比较不会自动转换数据类型
,比较值的同时比较数据类型是否相等;

      != 不相等,比较值是否不相等;

      !== 不相等,比较值的同时比较数据类型是否不相等;

2)返回值:boolean 型;

3)由于 JS 设计缺陷,不要使用 == 比较,始终坚持使用 === 比较。


1
2
3
1false == 0;   // true
2false === 0;  // false
3

4)浮点数的相等比较 :浮点数在运算过程中会产生误差,计算机无法精确表示无限循环小数。要比较两个浮点数是否相等,只能计算它们之差的绝对值,是否小于某个阈值。


1
2
3
11 / 3 === (1 - 2 / 3); // false
2Math.abs(1 / 3 - (1 - 2 / 3)) &lt; 0.0000001; // true
3

4.5  三元操作符

1)语法:条件 ? 执行代码1 : 执行代码2。

2)说明:三元操作符可代替简单的 if 语句,如果条件成立,执行代码1,否则执行代码2。


1
2
3
4
1var score = prompt(&#x27;请输入你的成绩?&#x27;);
2var result = score &gt; 60 ? &#x27;及格&#x27;:&#x27;不及格&#x27;;
3alert(result);
4

4.6  逻辑操作符

4.6.1  逻辑与

1)&& 与,只要有一个条件不成立,返回为 false。

2)有一个操作数不是布尔值的情况,逻辑与操作就不一定返回值,此时它遵循下列规则:

     1、如果第一个操作数隐式类型转换后为 true,则返回第二个操作数;

     2、如果第一个操作数隐式类型转换后为 false,则返回第一个操作数;

     3、如果有一个操作数是 null、NaN、undefined,则返回 null、NaN、undefined;

4.6.2  逻辑或

1)|| 或,只要有一个条件成立,返回为 true。

2)有一个操作数不是布尔值的情况,逻辑或操作就不一定返回值,此时它遵循下列规则:

      1、如果第一个操作数隐式类型转换后为 true,则返回第一个操作数;

      2、如果第一个操作数隐式类型转换后为 false,则返回第二个操作数;

      3、如果有两个操作数是 null、NaN、undefined,则返回 null、NaN、undefined;

4.6.3  逻辑非

1)!非、!!非。

2)无论操作数是什么数据类型,逻辑非都会返回一个布尔值。

3)说明:!! 同时使用两个逻辑非操作符,第1个逻辑非无论基于什么操作都会返回一个布尔值,第2个逻辑非则对该布尔值求反。

注:逻辑与、逻辑或、逻辑非返回的都是布尔值。

二、JS流程控制语句

1、JS分支语句:

if语句、switch多条件判断语句、prompt、alert、string.length。

1.1  if 语句


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1//语句一
2if(条件){
3     //执行代码块 一行代码的情况下,大括号可以省略但是不建议这样写
4}
5
6//语句二
7if(条件){
8    //执行代码块1
9}else{
10    //执行代码块2
11}
12
13//语句三
14if(条件){
15    //执行代码块1 
16}else if(条件){
17    //执行代码块2
18}else{
19    //执行代码块3
20}
21

案例:判断用户输入的密码是否是 6 位的纯数字,如果不是 6 位的纯数字,提示用户输入错误。


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
1var password = prompt(&#x27;请输入密码&#x27;);
2
3// 最佳方案
4if(isNaN(password) || password.length != 6){
5  alert(&#x27;密码长度必须是6位的纯数字&#x27;)
6}else{
7  alert(&#x27;密码输入正确&#x27;);
8}
9
10// 方法一
11if (password.length != 6) { // 判断密码的长度
12    alert(&#x27;密码长度必须是6位数字&#x27;);
13}else{
14    if (isNaN(password)) {
15        alert(&#x27;密码必须是数字&#x27;);
16    } else {
17        alert(&#x27;密码输入正确&#x27;);
18    }
19}
20
21// 方法二
22if(isNaN(password)){
23  alert(&#x27;密码必须是数字&#x27;);
24}else if(password.length != 6){
25  alert(&#x27;密码必须是6位数字&#x27;);
26}else{
27  alert(&#x27;密码输入正确&#x27;);
28}
29
30
31

案例:判断用户输入的密码是否是 6-12 位纯数字。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1var password=prompt(&#x27;请输入密码&#x27;);
2
3//方法一
4if(isNaN(password) || password.length &lt; 6 || password.length &gt; 12){
5  alert(&#x27;密码长度必须是6-12位的纯数字&#x27;);
6}else{
7  alert(&#x27;密码输入正确&#x27;);
8}
9
10//方法二
11if (password.length &lt; 6 || password.length &gt; 12) {
12    alert(&#x27;密码长度必须是6-12位数字&#x27;);
13}else{
14    if (isNaN(password)) {
15        alert(&#x27;密码必须是数字&#x27;);
16     } else {
17        alert(&#x27;密码输入正确&#x27;);
18     }
19}
20
21

1.2  switch 多条件判断语句


1
2
3
4
5
6
7
8
9
1    switch(表达式){
2        case value: 
3        statement;
4        break;
5        ……
6        default: 
7        statement;
8    }
9

Δ 
文本框中输入的值( 数字或文字 )都为字符串类型。

1.2.1  获取星期

1)语法:new Date().getDay()。

2)返回值: number,0 – 6 的数字。0 表示星期天。

案例:输出星期。


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
1var week = new Date().getDay(),
2    weekstr = &quot;&quot;;
3switch(week){
4  case 0:
5  weekstr = &#x27;日&#x27;;
6  break;
7
8  case 1:
9  weekstr = &#x27;一&#x27;;
10  break;
11
12  case 2:
13  weekstr = &#x27;二&#x27;;
14  break;
15
16  case 3:
17  weekstr = &#x27;三&#x27;;
18  break;
19
20  case 4:
21  weekstr = &#x27;四&#x27;;
22  break;
23
24  case 5:
25  weekstr = &#x27;五&#x27;;
26  break;
27
28  default:
29  weekstr = &#x27;六&#x27;;
30}
31document.write(&#x27;今天是星期&#x27; + weekstr);
32

案例:判断学生输入的成绩 0-100 之间纯数字,成绩小于 0 或者大于 100 表示成绩输入错误,成绩小于 60 不及格、60-70 及格、70-80 良好、80 以上优秀。


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
1var score = prompt(&#x27;输入你的成绩&#x27;);
2if(isNaN(score)){
3    alert(&#x27;输入的成绩必须是数字&#x27;);
4}else{
5    if(score &lt; 0 || score &gt; 100){
6        alert(&#x27;输入的成绩有误&#x27;);
7    }else {
8        switch(parseInt(score/10)){
9            case 0:
10            case 1:
11            case 2:
12            case 3:
13            case 4:
14            case 5:
15            document.write(&#x27;不及格&#x27;);
16            break;
17
18            case 6:
19            document.write(&#x27;及格&#x27;);
20            break;
21
22            case 7:
23            document.write(&#x27;良好&#x27;);
24            break;
25
26            default:
27            document.write(&#x27;优秀&#x27;);
28        }
29    }
30}
31

1.3  弹出框和字符串的长度 

1)prompt() 可以让用户在页面弹出的输入框中输入内容。
弹出输入框,点击确定,返回输入内容;点击取消,返回 null。

2)alert:弹出警告框。

3)length:string.length,获取 string 字符串的长度,返回值 number。

2、JS循环语句

for循环、for循环规则、while循环、do…while循环、for和while区别、break退出当前循环、continue跳过本次循环。

2.1  for 循环


1
2
3
4
1for(语句1; 语句2; 语句3){
2    //被执行的代码块;
3}
4
  • 语句1:循环代码块开始前执行;
  • 语句2:定义运行循环代码块的条件;
  • 语句3:循环代码块已被执行之后执行。

2.1.1  当循环与循环发生嵌套时遵循下列规则:

外层为假时内层不执行;先执行外层再执行内层,直至内层的条件为假时再返回外层去执行;

案例:九九乘法表。


1
2
3
4
5
6
7
8
1//九九乘法表
2for(var i=1; i&lt;=9; i++){
3    for(var j=1; j&lt;=i; j++){
4        document.write(j + &#x27;*&#x27; + i + &#x27;=&#x27; + j*i + &#x27;  &#x27;);
5    }
6    document.write(&#x27;&lt;br&gt;&#x27;);
7}
8

案例:水仙花每个位数上数字的 n 次幂之和等于它本身,例:1*1*1+5*5*5+3*3*3=153;在页面中输出 1000 以内的水仙花数。


1
2
3
4
5
6
7
8
9
10
11
12
13
1//水仙花153 370 371 407
2for(var bai=1; bai&lt;=9; bai++){
3    for (var shi=0; shi&lt;=9; shi++) {
4        for (var ge=0; ge&lt;=9; ge++) {
5            var result1=bai*bai*bai + shi*shi*shi + ge*ge*ge;
6            var result2=bai*100 + shi*10 + ge*1;
7            if (result1===result2) {
8              document.write(result1 + &#x27;&lt;br&gt;&#x27;);
9            }
10        }
11    }
12}
13

2.2  while 循环:


1
2
3
4
5
1while(条件){
2    //执行代码;
3    //变量变化语句;
4}
5

注: 变量变化语句一定要写,不然会造成死循环,页面会崩溃;

2.3  do-while 循环:


1
2
3
4
5
1do{
2    //需要执行的代码;
3    //变量变化语句;
4} while(条件)
5

do-while 循环在检查条件是否为真时,至少先执行一次代码块;如果为真继续循环,如果为假,不再循环。

2.4  for 与 while 的区别:

for 适合已知循环次数的循环体,while 适合未知循环次数的循环体。

案例:输出 1-10 的偶数、输出 1-100 的和。


1
2
3
4
5
6
7
8
9
10
11
12
13
1// 输出1-10的偶数
2for(var i=1; i&lt;=10; i++){
3    if(i%2 == 0) {
4        document.write(i + &#x27;&lt;br/&gt;&#x27;);
5    }
6}
7
8// 输出1-100的和 5050
9for(var i=1, sum=0; i&lt;=100; i++){
10    sum += i;
11}
12document.write(sum);
13

2.5  break 语句

立即退出循环。

案例:完成一个验证密码的代码,默认密码是123456,要求如下。

1)打开页面时,弹出第一个输入框,当用户输入的密码是默认密码时,弹出下一个输入框”请再次输入密码“;

2)如果用户输入的密码不是默认密码,那么重新弹出第一个输入框,直到密码输入正确,那么才弹出第二个输入框;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1//方法一
2var defaultpwd = &#x27;123456&#x27;,
3    pwdAgain;
4do{
5  var pwd=prompt(&#x27;请输入密码&#x27;);
6  if(pwd == defaultpwd){
7    break;
8  }
9}while(pwd != defaultpwd)
10pwdAgain=prompt(&#x27;请再次输入密码&#x27;);
11
12//方法二
13var pwd = prompt(&#x27;请输入密码&#x27;),
14    defaultpwd = &#x27;123456&#x27;,
15    pwdAgain;
16while (pwd != defaultpwd) {
17  pwd = prompt(&#x27;请输入密码&#x27;);
18  if(pwd == defaultpwd) {
19    break;
20  }
21}
22pwdAgain = prompt(&#x27;请再次输入密码&#x27;)
23

2.6  continue 语句

结束本次循环,继续开始下一次。

案例:打印所有 0-100 之间除了 22,44,66 以及 88 之外 2 的倍数,并求他们的和。


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
1//方法一
2var sum = 0;
3for(var i=0; i&lt;=100; i++){
4  if (i%2 == 0) {
5    if (i==22 || i==44 || i==66 || i==88) {
6      continue;
7    }
8    sum = sum + i;
9  }
10}
11document.write(sum);
12
13//方法二
14var sum = 0;
15for (var i = 0; i &lt;= 100; i++) {
16  if(i%2 == 0){
17    switch (i) {
18      case 22:
19      case 44:
20      case 66:
21      case 88:
22      continue;
23    }
24    sum = sum + i;
25  }
26}
27document.write(sum);
28

三、JS函数

函数的作用、函数的定义、函数的语法、函数的调用、函数的返回值、return语句说明、arguments函数的参数对象。

1.1  函数的作用

函数可以封装任意多条语句,可以在任何地方、任何时候调用执行。

1.2  函数的定义

函数使用 function 声明,后跟一组参数一级函数体。

1.3  函数的语法


1
2
3
4
1function functionName([arg0,arg1…argn]){
2   //执行脚本;
3}
4
  •     functionName 要定义的函数名,属于标识符;
  •     [ ] 中的 arg0,arg1…argn 为函数的参数,不是必须的;
  •     [ ] 只说明里面的内容不是必须的,它不是语法。

1.4  函数的调用

直接写函数名 functionName([arg0,arg1…argn])。

1.5  函数的返回值

任何函数在任何时候都可以通过 return 语句后跟要返回的值来实现返回值。

1.6  return 语句说明

1)函数会在执行完 return 语句之后停止并立即退出;

2)return 语句可以不带有任何返回值,一般用于需要提前停止函数执行而又不需要返回值的情况;

3)如果希望函数值能返回调用它的地方,我们可以使用 return 后面加上返回值;

4)return 后面如果有返回值,那么函数读到它时,会停止执行,并返回制定的值;

5)return 后面如果没有返回值,那么函数会在执行 return 语句后停止并立即退出。

案例:利用函数对用户输入的密码长度进行判断,密码长度 6-12 位。


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
1var password=prompt(&#x27;请输入密码&#x27;);
2
3// 方法一
4function num(password){
5   var length = password.length;
6   if(length &lt; 6 || length &gt; 12){
7      return &#x27;密码必须是6-12位&#x27;
8    }
9    return &#x27;密码输入正确&#x27;;
10}
11
12
13// 方法二
14function num(password){
15  if (password.length &gt;= 6 &amp;&amp; password.length &lt;= 12) {
16    return &#x27;密码输入正确&#x27;;
17  }else {
18    return &#x27;密码必须是6-12位&#x27;;
19  }
20}
21
22// 方法三
23function num(password){
24  if (password.length&lt;6) {
25    return &#x27;密码长度不能小于6位数&#x27;;
26  }else if (password.length&gt;12) {
27    return &#x27;密码长度不能大于12位数&#x27;;
28  }else {
29    return &#x27;密码输入正确&#x27;;
30  }
31}
32
33var result=num(password);
34document.write(result);
35

1.7  arguments

在 ECMAScript 中的参数内部用一个数组来表示,在函数体内通过 ECMAScript 对象来访问这个数组参数。

arguments 对象只是与数组类似,并不是 Array 的实例。[ ] 访问它的每一个元素。length 属性确定传递参数的个数。
arguments.length 获取函数参数长度。arguments[1] 访问函数参数元素。


1
2
3
4
5
6
7
8
9
10
11
12
1function inner(){
2  console.log(arguments.length); //2
3  console.log(arguments[1]); //5
4}
5inner(10,5);
6
7function add(num1, num2){
8    arguments[0]=99;
9    console.log(num1); //99
10}
11add(55,88)
12

案例:用 arguments 对象获取到函数参数任意一组数的平均值,且这个平均值是一个整数。


1
2
3
4
5
6
7
8
9
10
1function num(){
2  var sum = 0, len = arguments.length;
3  for(var i=0; i&lt;len; i++){
4    sum += arguments[i]
5  }
6  return parseInt(sum/len);
7}
8var result = num(2,4,6,1);
9document.write(result);
10

案例:函数参数对象 arguments,使用函数的 arguments 来做下用户密码和验证码的验证。用户输入的密码不是数字时,提示“密码错误”。用户输入的验证码小于 4 位数时,提示“验证码不得小于 4 位数”。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1var pwd = prompt(&#x27;请输入密码&#x27;), code;
2function  login(pwd,code) {
3  if(isNaN(arguments[0])){
4    return &#x27;密码必须是数字&#x27;;
5  }else{
6    code=prompt(&#x27;请输入验证码&#x27;);
7    if(arguments[1].length&lt;4){
8      return &#x27;验证码长度不能小于4位数&#x27;;
9    }
10  }
11  return &#x27;密码输入正确&#x27;;
12}
13
14var result = login(pwd, code);
15document.write(result);
16

四、内置对象

1、JS中的数组

创建数组的2种方式、数组元素的读写、数组的长度;
数组栈方法:  push()、pop()、unshift()、shift();
数组转换方法:join() 数组转换成字符串、reverse() 数组取返;

数组重新排序:sort();
数组的操作方法concat()、slice(start, end)可以实现数组的拷贝、splice()删除插入替换数组项;
数组实例添加的两个位置方法indexOf(searchValue, startIndex)、lastIndexOf(searchValue, startIndex)搜索某个值在数组中出现的位置,没有找到的情况下返回-1。

1.1 数组

1.1.1  创建数组 2 种方式

1)使用 Array 构造函数:new Array()。

小括号 () 说明:预先知道数组要保存的项目数量,向 Array 构造函数中传递数组应包含的项。


1
2
3
4
5
6
7
8
9
1var colors = new Array(3); //数组项目数量
2    colors[0] = &quot;#f00&quot;;
3    colors[1] = &quot;#0f0&quot;;
4    colors[2] = &quot;#00f&quot;;
5console.log(colors);
6
7var num = new Array(1,2,3,4); //数组应包含的项
8console.log(num);
9

2)使用数组字面量表示法:由一对包含数组项的中括号 [ ] 表示,多个数组项之间用逗号隔开。


1
2
3
4
1var info = [6,&#x27;marry&#x27;,true];
2console.log(info[5]); //索引超出了范围,返回 undefined
3console.log(info.length); //3
4

1.1.2  数组元素的读写

读取和设置值时,使用中括号 [ ] 并提供相应的索引。索引是从 0 开始的正整数。

1.1.3  数组长度

array.length,返回值 number。通过设置 length 可以从数组的末尾移除项或向数组中添加新项;当把一个值放在超出当前数组大小的位置上时,长度值等于最后一项索引加1。


1
2
3
4
5
6
7
8
9
1var arr = [&#x27;a&#x27;,&#x27;b&#x27;,&#x27;c&#x27;,&#x27;d&#x27;];
2console.log(arr.length);
3
4arr.length = 2;
5console.log(arr);
6
7arr[99]=&#x27;e&#x27;;
8console.log(arr.length);
9

数组遍历语法:


1
2
3
4
1for(var i=0; i&lt;arr.length; i++){
2  console.log(arr[i]);
3}
4

 
案例:编写一个统计员工工资的代码,要求不停接收用户输入的员工工资,直到用户输入“退出”便不再弹出“输入工资”窗口。把用户输入的数据存在一个数组中,数组中不包含“退出”。


1
2
3
4
5
6
7
8
9
10
11
12
13
1var arr = [],
2    i = 0,
3    money;
4
5while(money != &#x27;退出&#x27;) {
6  money = prompt(&#x27;请输入工资&#x27;);
7  arr[i] = money;
8  i++;
9}
10
11arr.length -= 1;
12console.log(arr);
13

1.2  数组栈方法

1.2.1  push() 

1)语法:arrayObject.push(newele1,newele2,…,neweleX)。

2)功能:
把它的参数顺序添加到数组对象的尾部。

3)返回值:
指定的值添加到数组后的新长度。


1
2
3
4
5
1var arr = [1,2,3,4,5];
2var push = arr.push(8);
3console.log(push); // 6
4console.log(arr); // [1,2,3,4,5,8]
5

案例:函数来封装一个数组,数组中所有大于 3 的值都取出来存到一个新数组中。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1var arr = [1,2,5,8,10,9,3,6],
2    newArr = [];
3
4function nums(arr){
5  for(var i=0; i&lt;arr.length; i++){
6    if(arr[i] &gt; 3) {
7        newArr.push(arr[i])
8    }
9  }
10  return newArr;
11}
12
13var result = nums(arr);
14console.log(result);
15

1.2.2  pop() 

1)语法:arrayObject.pop()。

2)功能:
删除数组对象最后一个元素。

3)返回值:
被删除的那个元素。


1
2
3
4
1var arr = [1,2,3,4,5];
2var pop = arr.pop();
3console.log(pop); //5
4

1.2.3  unshift() 

1)语法:arrayObject.unshift(newele1,newele2,…,neweleX)

2)功能:
把它的参数顺序添加到数组对象的开头。

3)返回值:指定的值添加到数组后的新长度。


1
2
3
4
1var arr = [1,2,3,4,5]
2var unshift = arr.unshift(0);
3console.log(unshift); // 6
4

1.2.4  shift() :

1)语法:arrayObject.shift()

2)功能:
删除数组对象第一个元素。

3)返回值:被删除的那个元素。


1
2
3
4
1var arr = [1,2,3,4,5];
2var shift = arr.shift();
3console.log(shift); //1
4

案例:封装一个函数,实现不用 reverse( ) 也能实现数组反转的功能。


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
1var arr = [1,2,3];
2console.log(arr.reverse());
3
4//方法一
5function reverseArr(arr){
6  var newArr = [];
7  for(var i=0; i&lt;arr.length; i++) {
8    newArr.unshift(arr[i]);
9  }
10  return newArr;
11}
12var newArr1 = reverseArr([1,2,3,4]);
13console.log(newArr1);
14
15//方法二
16function reverseArr(arr){
17  var newArr = [];
18  for(var i=arr.length-1; i&gt;=0; i--) {
19    newArr.push(arr[i]);
20  }
21  return newArr;
22}
23var newArr1 = reverseArr([1,2,3,4]);
24console.log(newArr1);
25

案例:写一个函数,返回某个值在这个数组中出现了多少次。 


1
2
3
4
5
6
7
8
9
10
11
12
13
1var nums = [8,2,5,6,8,6,7,9],
2    times = 0;
3function getTimes(arr,num){
4  for(var i=0; i&lt;arr.length; i++){
5    if(arr[i] === num) {
6      times += 1;
7    }
8  }
9  return times;
10}
11var result = getTimes(nums,8)
12console.log(result);
13

1.3  数组转换方法

1.3.1  join()

1)语法:arrayObject.join(separator)  separator 分隔符。

2)说明:
join 没有参数时,默认“,”分隔;如果不想值与值之间用任何东西隔开写个空的引号(“ ”)。

3)功能:
把数组中的所有元素都转换成字符串。

4)返回值:字符串。


1
2
3
4
5
6
7
8
9
10
1//join
2var num = [2,4,5];
3var str = num.join();
4console.log(str);
5
6var words = [&#x27;border&#x27;,&#x27;left&#x27;,&#x27;color&#x27;];
7var wordStr = words.join(&#x27;-&#x27;);
8console.log(wordStr);
9
10

1.3.2  reverse() 

1)语法:arrayObject.reverse()

2)功能:
颠倒数组中元素的顺序。

3)返回值:数组。


1
2
3
4
5
6
7
8
9
1//reverse
2var num = [2,4,5];
3num.reverse();
4console.log(num);
5
6var str = [&#x27;a&#x27;,&#x27;b&#x27;,&#x27;c&#x27;,&#x27;d&#x27;];
7var newStr = str.reverse().join(&#x27;&#x27;);
8console.log(newStr);
9

1.4  数组重新排序

1.4.1  sort() :

1)语法:arrayObject.sort(sortby)

2)功能:
对数组中的元素进行排序。

3)返回值:数组。

4)说明:
即使数组中的每一项都是数值,sort() 方法比较的也是字符串。sort() 方法可以接收一个比较函数作为参数。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1// sort
2var arr = [9,23,15,-99,88,12,-2];
3arr.sort(
4  function(a,b){
5    return a - b; // 升序
6  }
7)
8console.log(arr);
9
10arr.sort(
11  function(a,b){
12    return b - a; // 降序
13  }
14)
15console.log(arr);
16

案例:对用户输入的数据进行降序排序。要求用户输入的结束符 “-1” 不进行排序。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1var i=0,
2    num,
3    arr=[];
4while(num != &#x27;-1&#x27;){
5  num = prompt(&#x27;请输入数据&#x27;);
6  arr[i] = num;
7  i++;
8}
9arr.length -= 1;
10var result = arr.sort(function(a,b){
11      return a&lt;b;
12})
13console.log(result);
14

1.5  数组的操作方法

1.5.1  concat() 

1)语法:arrayObject.concat(arrayX,arrayX,…,arrayX)

2)功能:
连接两个或多个数组。

3)返回值:数组。


1
2
3
4
5
6
7
1var arr1 = [&#x27;a&#x27;,&#x27;b&#x27;,&#x27;c&#x27;],
2    arr2 = [&#x27;d&#x27;,&#x27;e&#x27;,1,3],
3    arr3;
4
5arr3 = arr1.concat(arr2,[4,5,6]);
6console.log(arr3);
7

1.5.2  slice() :

1)语法:arrayObject.slice(start,end)。

2)功能:
从已有的数组中返回选定的元素。

3)参数:start 必需,规定从何处开始选取。end 可选,规定从何处结束选取,start\end 数组下标。
如果没有指定 end,切分的数组包含从 start 到数组结束的所有元素。

                如果 slice() 方法的参数中有一个负数,则用数组长度加上该数组确定相应的位置。

      slice()的起止参数包括开始索引,不包括结束索引。如果不给 slice()传递任何参数,它就会从头到尾截取所有元素。利用这一点,可以复制一个 Array。

      数组中的slice()对应字符串中的substring()。

5)返回值:数组。


1
2
3
4
5
6
7
1var colors = [&#x27;red&#x27;,&#x27;green&#x27;,&#x27;blue&#x27;,&#x27;yellow&#x27;,&#x27;orange&#x27;];
2var newColors1 = colors.slice(1,4); //green,blue,yellow
3
4var newColors2 = colors.slice(-4,3); //green,blue
5console.log(newColors1);
6console.log(newColors2);
7

案例:完成以下代码段,实现 b 数组对 a 数组的拷贝,方法越多越好。 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1var a = [1,&#x27;yes&#x27;,3],
2    b = [];
3
4// 方法一:for循环 push
5for(var i=0; i&lt;a.length; i++){
6  b.push(a[i]);
7}
8
9// 方法二:concat()
10b = [].concat(a) //空数组 告诉它空数组和a的数组联系到一起
11
12// 方法三:slice()
13b = a.slice(0);
14
15// 方法四:splice()
16b = a.splice(0);
17
18console.log(b);
19

1.5.3  splice() 方法删除数组项:

1)语法:arrayObject.splice(index,count)

2)功能:删除从 index 处开始的零个或多个元素。

3)
返回值:含有被删除的元素的数组。

4)说明:
count 是要删除的项目数量,如果设置为0,则不会删除项目。如果不设置,则删除从 index 开始的所有值。


1
2
3
4
5
6
7
1//splice删除数组项    
2var arr = [&#x27;a&#x27;,&#x27;b&#x27;,&#x27;c&#x27;,&#x27;d&#x27;,&#x27;e&#x27;,&#x27;f&#x27;];
3var delArr = arr.splice(2,3);
4
5console.log(delArr); // [&quot;c&quot;, &quot;d&quot;, &quot;e&quot;]
6console.log(arr); // [&quot;a&quot;, &quot;b&quot;, &quot;f&quot;]
7

1.5.4   splice() 方法插入数组项:

1)语法:arrayObject.splice(index,0,item1,….,itemX)

2)功能:在指定位置插入值。

3)参数:index 起始位置、0 要删除的项数、item1,….,itemX 要插入的项。

4)
返回值:数组(返回的是空数组)。


1
2
3
4
5
6
7
1//插入数组项
2var arr = [&#x27;a&#x27;,&#x27;b&#x27;,&#x27;c&#x27;,&#x27;d&#x27;,&#x27;e&#x27;,&#x27;f&#x27;];
3var insertArr = arr.splice(1,0,&#x27;m&#x27;,&#x27;n&#x27;,9);
4
5console.log(insertArr); // []
6console.log(arr); // [&quot;a&quot;, &quot;m&quot;, &quot;n&quot;, 9, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;]
7

1.5.3  splice() 方法替换数组项:

1)语法:arrayObject.splice(index,count,item1,….,itemX)

2)功能:在指定位置插入值,且同时删除任意数量的项。

3)参数:index 起始位置、0 要删除的项数、item1,….,itemX 要插入的项。

4)返回值:从原始数组中删除的项(如果没有删除任何项,则返回空数组)。


1
2
3
4
5
6
7
1//替换数组项
2var arr = [&#x27;a&#x27;,&#x27;b&#x27;,&#x27;c&#x27;,&#x27;d&#x27;,&#x27;e&#x27;,&#x27;f&#x27;];  
3var replaceArr = arr.splice(1,2,&#x27;x&#x27;,&#x27;y&#x27;,&#x27;z&#x27;);
4
5console.log(replaceArr); // [&quot;b&quot;, &quot;c&quot;]
6console.log(arr) // [&quot;a&quot;, &quot;x&quot;, &quot;y&quot;, &quot;z&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;]
7

案例:输入任意你喜欢的字符,使用数组的操作方法写出代码。

1)循环弹出输入框,用户输入的任意字符的前两个被替换为 “hello”,后面的字符不受影响。

2)当输入 “-1” 时,输入框停止弹出。数组中不包含结束字符 -1。


1
2
3
4
5
6
7
8
9
10
11
12
13
1var text,
2    arr=[],
3    i=0;
4while(text != &#x27;-1&#x27;){
5  text=prompt(&#x27;输入你喜欢的字符&#x27;);
6  arr[i]=text;
7  i++;
8}
9arr.length-=1;
10var newArr=arr.splice(0,2,&#x27;hello&#x27;)
11console.log(arr);
12console.log(newArr);
13

1.6  数组实例添加的两个位置方法:

1.6.1   indexOf()

1)语法:arrayObject.indexOf(searchvalue,startIndex)

2)功能:从数组的开头(位置0)开始向后查找。

3)参数:searchvalue 必需,要查找的项;startIndex 可选,起点位置的索引。

4)
返回值:number,查找的项在数组中的位置,没有找到的情况下返回 -1。

1.6.2   lastIndexOf()

1)语法:arrayObject.lastIndexOf(searchvalue,startIndex)

2)功能:从数组的末尾开始向前查找。

3)参数:searchvalue 必需,要查找的项;startIndex 可选,起点位置的索引。

4)返回值:number,查找的项在数组中的位置,没有找到的情况下返回 -1。

5)说明:
在比较第一个参数与数组中的每一项时,会使用全等操作符,即要求查找的项必须严格相等。数组的位置方法是 ECMAScript5 为数组实例新增的,支持的浏览器只有:IE9、Firefox2+、Safari3+、Opera9.5 和 Chrome。

案例:数组的 indexOf() 方法有兼容性问题,考虑到低版本浏览器兼容性,需要自己写一个函数封装这个方法。

1)写出函数,定义两个参数,一个是要被检测的数组,另一个是要判断的值。

2)函数里面要对被检测的数组进行循环,判断如果数组里的项等于要判断的值,那么返回这个数组项的索引。


1
2
3
4
5
6
7
8
9
10
11
12
1var nums = [1,7,5,7,8,1,6,9];
2function arrIndexOf(arr,value){
3  for(var i=0; i&lt;arr.length; i++){
4    if (arr[i] === value) {
5      return i;
6    }
7  }
8  return -1;
9}
10var pos = arrIndexOf(nums,7);
11console.log(pos);
12

2、JS中的String

常用字符串 charAt(index) index是索引值、charCodeAt(index)、indexOf()、lastIndexOf();截取字符串方法 slice(start, end)、substring(start, end)、substr(start,len);字符串对象方法 split()、replace();字符串其它方法 toUpperCase()、toLowerCase()。

2.1  常用字符串

2.1.1  charAt()

1)语法:stringObject.charAt(index) 。

2)功能:返回 stringObject 中 index(索引)位置的字符。

2.1.2  charCodeAt()

1)语法:stringObject.charCodeAt(index) 。

2)功能:返回 stringObject 中 index(索引)位置字符的字符编码。


1
2
3
4
1var str = &#x27;hello world&#x27;;
2var a = str.charAt(1); //e
3var b = str.charCodeAt(1); //101 字符对应的字符编码
4

2.1.3  indexOf()

1)语法:stringObject.indexOf("o") 。

2)功能:从一个字符串中搜索给定的子字符串,返回子字符串的位置。

3)返回值:数值。

4)说明:如果没有找到该子字符串,则返回 -1。

2.1.4  lastIndexOf()

1)语法:stringObject.lastindexOf("o")

2)功能:从一个字符串尾部搜索给定的子字符串,返回子字符串的位置。

3)返回值:数值

4)说明:如果没有找到该子字符串,则返回 -1。


1
2
3
4
1var str = &#x27;hello world&#x27;;
2var c = str.indexOf(&#x27;o&#x27;); //4
3var d = str.lastIndexOf(&#x27;o&#x27;); //7
4

2.2  截取字符串方法

2.2.1   slice()

1)语法:stringValue.slice(start,end)

2)功能:截取子字符串

3)参数说明:start 必需,指定子字符串的开始位置。

                       end 可选,表示子字符串到哪里结束,
end 本身不在截取范围之内,省略时截取至字符串的末尾。

                       
当参数为负数时,会将传入的负值与字符串的长度相加。

2.2.2   substring()

1)说明:语法及功能同 slice() 完全一样。

2)区别在于:当参数为负数时,自动将参数转换为 0;

                        substring() 会将较小的数作为开始位置,将较大的数作为结束位置。


1
2
3
4
1var str = &#x27;hello world&#x27;;
2var a = str.substring(-7,5); //0,5
3var b = str.substring(2,-5); //0,2
4

2.2.3   substr()

1)语法:stringValue.substr(start,len)

2)功能:截取子字符串。

3)参数说明:start 必需,指定子字符串的开始位置。

                        len:可选,表示截取的字符总数,省略时截取至字符串的末尾。

                        当 start 为负数时,会将传入的负值与字符串的长度相加。

                       
当 len 为负数时,返回空字符串。


1
2
3
4
5
1var str = &#x27;hello world&#x27;;
2var a = str.slice(0,2);  // he
3var b = str.substring(0, 4);  // hell
4var c = str.substr(1,-1); //
5

2.3  字符串对象方法

2.3.1   split()

1)语法:stringObject.split(separator)

2)功能:
把一个字符串分割成字符串数组。

3)返回值:Array。

4)说明:separator 必需,分隔符。
如果把空字符串 (' ') 用作 separator,那么 stringObject 中的每个字符之间都会被分割。


1
2
3
4
1var str = &#x27;border-left-color&#x27;;
2var a = str.split(&#x27;-&#x27;); //[&quot;border&quot;, &quot;left&quot;, &quot;color&quot;];
3var b = str.split(&#x27;&#x27;);
4

2.3.2   replace()

1)语法:stringObject.replace(regexp/substr,replacement) (替换谁,被替换成谁)

2)功能:
在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的字串。

3)返回值:String

4)参数:regexp 必需。规定子字符串或要替换的模式的 RegExp 对象。

                replacement 必需,一个字符串值。


1
2
3
4
5
1//字符串对象方法
2var str = &#x27;hello world&#x27;;
3var a = str.split(&#x27;&#x27;);
4var b = str.replace(&#x27;e&#x27;,&#x27;cc&#x27;);
5

2.4  字符串其它方法

2.4.1   toUpperCase()

1)语法:stringValue.toUpperCase()

2)功能:把字符串转换为大写。

2.4.2   toLowerCase()

1)语法:stringValue.toLowerCase()

2)功能:把字符串转换为小写。

案例:用函数封装,将字符串 border-left-color 转换成 borderLeftColor。


1
2
3
4
5
6
7
8
9
10
11
1function text(str){
2  var arr = str.split(&#x27;-&#x27;), newStr = arr[0]; //[&quot;border&quot;, &quot;left&quot;, &quot;color&quot;]
3  for(var i=1; i&lt;arr.length; i++){
4    var word = arr[i];
5    newStr += word.charAt(0).toUpperCase() + word.substr(1);
6  }
7  return newStr;
8}
9var newText = text(&#x27;border-left-color&#x27;);
10console.log(newText);
11

3、JS中的Math

Math.max()、Math.ceil()、Math.floor()、Math.round()、Math.abs()、Math.random()、随机整数封装在函数中公式。

3.1   Math.max()

1)语法:Math.max(num1,num1…numN);

2)功能:
求一组数中的最大值;

3)返回值:Number。

3.2   Math.ceil()

1)语法:Math.ceil(num);

2)功能:向上取整,即返回大于 num 的最小整数;

3)返回值:Number。

3.3   Math.floor()

1)语法:Math.floor(num);

2)功能:向下取整,返回 num 的整数部分;

3)返回值:Number。

3.4   Math.round()

1)语法:Math.round(num);

2)功能:
将数值四舍五入为最接近的整数;

3)返回值:Number。

3.5   Math.abs()

1)语法:Math.abs(num);

2)功能:返回 num 的绝对值;

3)返回值:Number。

3.6   Math.random()

1)语法:Math.random();

2)功能:返回大于等于 0 小于 1 的一个随机数;

3)返回值:Number。

4)说明:
封装一个求 n 到 m 之间的随机整数的函数,求 n 和 m 之间的随机整数的公式,random = Math.floor(Math.random()*(m-n+1)+n),m-n+1 是随机整数的个数。


1
2
3
4
5
6
7
8
9
10
11
1var min = Math.min(1,2,-3,4); //-3
2var max = Math.max(1,2,-3,4); //4
3//生成一个n到m之间的随机整数
4function getRandom(n,m){
5  var choise = m-n+1; //随机整数的个数
6  console.log(choise);
7  return Math.floor(Math.random() * choise + n);
8}
9var random1 = getRandom(2,6);
10console.log(random1);
11

案例:随机产生 10 个整数,放入数组中,对这个数组进行降序排序,并获取到这个数组的最大值和最小值。(利用循环,获取10 个整数)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1var arr = [];
2function getRandom(n,m){
3  var choise = m-n+1;
4  return Math.floor(Math.random() * choise + n);
5}
6for(var i=0; i&lt;10; i++){
7  //生成一个随机数
8  var random = getRandom(0,100);
9  //将生成的随机数放入数组内
10  arr.push(random);
11}
12var newArr = arr.sort(function(a,b){ return a&lt;b;});
13console.log(newArr);
14
15var str = newArr.join();
16var max = Math.floor(parseInt(str))
17console.log(max);
18

4、JS中的Date对象

创建一个日期对象 new Date()、new Date().getDate()、new Date().getDay()。

4.1   创建一个日期对象

1)语法:new Date();

2)功能:创建一个日期时间对象;

3)返回值:不参与的情况下,返回当前的日期时间对象;

4)说明:如果想根据特定的日期和时间创建日期对象,必需传入表示该日期的毫秒数或者是一组用逗号隔开的表示年月日时分秒的参数。

4.2  获取年月时分秒及星期的方法

1、getFullYear():返回 4 位数的年份;

2、getMonth():返回日期中的月份,返回值为 0-11(0表示1月);

3、getDate():
返回月份中的天数;

4、getDay():返回星期,返回值为 0-6;

5、getHours():返回小时;

6、getMinutes():返回分钟;

7、getSeconds():返回秒;

8、getTime():返回表示日期的毫秒数。

4.3  设置年月时分秒及星期的方法

1、setFullYear(year):设置 4 位数的年份

2、setMonth(mon):设置日期中的月份,从 0 开始,0 表示 1 月份

3、setDate():设置日期

4、setDay():设置星期,从 0 开始,0 表示星期日

5、setHours():设置小时

6、setMinutes():设置分

7、setSeconds():设置秒

8、setTime():以毫秒数设置日期,会改变整个日期

案例:50 天之后是星期几。


1
2
3
4
1var day = (50+1)%7;
2var week = [&#x27;日&#x27;,&#x27;一&#x27;,&#x27;二&#x27;,&#x27;三&#x27;,&#x27;四&#x27;,&#x27;五&#x27;,&#x27;六&#x27;];
3console.log(&#x27;50天后是星期&#x27;+week[day]);
4

五、DOM基础

DOM查找方法document.getElementById()、document.getElementsByTagName()、document.getElementsByName()、document.getElementsByClassName();设置元素样式ele.style.styleName=styleValue、替换元素内容ele.innerHTML、重新设置元素的类 ele.className=“cls”;

DOM属性获取 ele.getAttribute()、设置ele.setAttribute()、删除ele.removeAttribute()。

1、DOM查找方法

1.1  document.getElementById()

1)语法:document.getElementById(“id”);

2)功能:返回对拥有指定 ID 第一个对象的引用;

3)返回值:DOM 对象;

4)说明:id 为 DOM 元素上 id 属性的值。

1.2  document.getElementsByTagName()

1)语法:document.getElementsByTagName(“tag”);

2)功能:
返回一个对所有 tag 标签引用的集合;

3)返回值:数组;

4)说明:tag 为要获取的标签名称;

5)document.getElementsByName() 返回指定 name 属性值的所有子元素的集合,返回的是一个类数组对象;

6)document.getElementsByClassName() 返回指定 class 名称的元素(
不管元素上有没有类,className 属性设置的类会重写元素上的类)。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1&lt;div class=&quot;box&quot; id=&quot;box&quot;&gt;盒子&lt;/div&gt;
2&lt;ul id=&quot;list1&quot;&gt;
3  &lt;li&gt;函数&lt;/li&gt;
4  &lt;li&gt;数组&lt;/li&gt;
5&lt;/ul&gt;
6&lt;ol&gt;
7  &lt;li&gt;js&lt;/li&gt;
8  &lt;li&gt;vue&lt;/li&gt;
9&lt;/ol&gt;
10
11&lt;script&gt;
12  var box = document.getElementById(&#x27;box&#x27;);
13  console.log(box);
14
15  var list = document.getElementsByTagName(&#x27;li&#x27;);
16  console.log(list.length);  // 4
17
18  var list1 = document.getElementById(&#x27;list1&#x27;).getElementsByTagName(&#x27;li&#x27;);
19  console.log(list1.length);  // 2
20&lt;/script&gt;
21

1.3  设置元素样式

1)语法:ele.style.styleName = styleValue;

2)功能:设置 ele 元素的 CSS 样式;

3)说明:ele 为要设置样式的 DOM 对象,styleName 为要设置的样式名称必须使用驼峰形式,styleValue 为要设置的样式值。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1    &lt;div class=&quot;box&quot; id=&quot;box&quot;&gt;DOM基础&lt;/div&gt;
2    &lt;ul id=&quot;list&quot;&gt;
3      &lt;li&gt;函数&lt;/li&gt;
4      &lt;li&gt;数组&lt;/li&gt;
5      &lt;li&gt;对象&lt;/li&gt;
6    &lt;/ul&gt;
7    &lt;script&gt;
8      var list = document.getElementById(&#x27;list&#x27;).getElementsByTagName(&#x27;li&#x27;);
9      for(var i=0; i&lt;list.length; i++){
10        if(i==0){
11          list[i].style.color = &quot;#f00&quot;;
12        }else if(i==1){
13          list[i].style.color = &quot;#f0f&quot;;
14        }else{
15          list[i].style.color = &#x27;#00f&#x27;};
16      }
17    &lt;/script&gt;
18

1.4  标签之间内容替换 innerHTML

1)语法:ele.innerHTML;

2)功能:
返回 ele 元素开始和结束标签之间的内容;

3)语法:ele.innerHTML = “html”;

4)功能:设置 ele 元素开始和结束标签之间的 HTML 内容为 html;

5)说明:innerHTML 获取和设置标签之间的文本和 html 内容。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1&lt;style&gt;
2  .current{color:#f00;}
3&lt;/style&gt;
4&lt;div class=&quot;box&quot; id=&quot;box&quot;&gt;DOM基础&lt;/div&gt;
5&lt;ul id=&quot;list&quot;&gt;
6  &lt;li&gt;函数&lt;/li&gt;
7  &lt;li&gt;数组&lt;/li&gt;
8  &lt;li&gt;对象&lt;/li&gt;
9&lt;/ul&gt;
10&lt;script&gt;
11  var list = document.getElementById(&#x27;list&#x27;).getElementsByTagName(&#x27;li&#x27;);
12  for(var i=0; i&lt; list.length; i++){
13    console.log(list[i]);
14    list[i].innerHTML = list[i].innerHTML + &#x27;是JS的一部分&#x27;;
15    list[1].className = &quot;current&quot;;
16  }
17&lt;/script&gt;
18

1.5  重新设置类 className

1)语法:ele.className;

2)功能:
返回 ele 元素的 class 属性;

3)语法:ele.className = “cls”;

4)功能:
设置 ele 元素的 class 属性为 cls;

5)说明:
动态添加 class 替换元素本身的 class,ele.className 是重新设置类,替换元素本身的 class。如果元素有 2 个以上的class 属性值,那么获取这个元素的 className 属性时,会将它的 class 属性值都打印出来。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1&lt;style&gt;
2  .box{ background: #f6f6f6; }
3  .box1{ padding: 10px; }
4&lt;/style&gt;
5&lt;div class=&quot;box&quot; id=&quot;box&quot;&gt;盒子&lt;/div&gt;
6&lt;ul id=&quot;list1&quot;&gt;
7  &lt;li&gt;函数&lt;/li&gt;
8  &lt;li&gt;数组&lt;/li&gt;
9&lt;/ul&gt;
10&lt;ol&gt;
11  &lt;li&gt;js&lt;/li&gt;
12  &lt;li&gt;vue&lt;/li&gt;
13&lt;/ol&gt;
14
15&lt;script&gt;
16  var box = document.getElementById(&#x27;box&#x27;);
17  box.style.color = &#x27;#f00&#x27;;
18  box.innerHTML = &#x27;模型&#x27;;
19  box.className = &#x27;box1&#x27;;
20&lt;/script&gt;
21

2、DOM属性设置与获取

2.1   获取属性

1)语法:ele.getAttribute(“attribute”)

2)功能:获取 ele 元素的 attribute

3)说明:ele 是要操作的 dom 对象,attribute 是要获取的 html 属性。

2.2   设置属性

1)语法:ele.setAttribute(“attribute”,  value)

2)功能:在 ele 元素上设置属性

3)说明:ele 是要操作的 dom 对象,attribute 设置的属性名,value 的attribute属性值。

2.3    删除属性

1)语法:ele.removeAttribute(“attribute”)

2)功能:删除 ele 上的 attribute 属性

3)说明:ele 是要操作的 dom 对象,attribute 是要删除的属性名。


1
2
3
4
5
6
7
8
9
10
11
12
1&lt;p id=&quot;text&quot; class=&quot;text&quot; align=&quot;center&quot; data-type=&quot;title&quot;&gt;文本&lt;/p&gt;
2&lt;input type=&quot;text&quot; name=&quot;user&quot; value=&quot;user&quot; id=&quot;user&quot; validate=&quot;true&quot;&gt;
3
4&lt;script&gt;
5  var p = document.getElementById(&#x27;text&#x27;);
6  var user = document.getElementById(&#x27;user&#x27;);
7  console.log(p.getAttribute(&#x27;class&#x27;));
8  console.log(user.getAttribute(&#x27;validate&#x27;));
9  p.setAttribute(&#x27;data-color&#x27;,&#x27;red&#x27;);
10  p.removeAttribute(&#x27;align&#x27;);
11&lt;/script&gt;
12

六、DOM事件

什么是事件、HTML事件、DOM0级事件执行脚本可以是匿名函数也可以是函数的调用、鼠标事件、键盘事件与keyCode属性、关于this指向、手机号判断value用户获取表单中的值j、皮肤颜色改变、判断浏览器窗口和滚动条发生变化、按钮的交互变化、多行文本框输入字符计算。

1、什么是事件

事件是文档或浏览器窗口中发生的一些特定的交互瞬间。

2、HTML 事件

1)语法:
<tag 事件=“执行脚本”></tag>

2)功能:在 HTML 元素上绑定事件;

3)说明:执行脚本可以是一个函数的调用;

4)不建议使用 HTML 事件原因:多元素绑定相同事件时,效率低;不建议在 HTML 元素中写 JavaScript 代码。

3、DOM0 级事件:

1)通过 DOM 获取 HTML 元素;

2)语法:ele.事件 = 执行脚本;

3)功能:在 DOM 对象上绑定事件;

4)说明:
执行脚本可以是一个匿名函数,也可以是一个函数的调用。

4、鼠标事件:

onload:页面加载时触发;

onclick:鼠标点击时触发;

onmouseover:鼠标滑过时触发;

onmouseout:鼠标离开时触发;


onfocus:获得焦点时触发(onfocus 事件用于 input 标签 type 为 text、password、textarea 标签);

onblur:失去焦点时触发;

案例:手机号判断。


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
1    &lt;style&gt;
2       .tip{display:none;font-size:14px; vertical-align: middle; padding-top: 3px}
3    &lt;/style&gt;
4    &lt;script&gt;
5        window.οnlοad=function(){
6          var phone=document.getElementById(&quot;phone&quot;),
7              tip=document.getElementById(&quot;tip&quot;);
8          phone.οnfοcus=function(){
9              tip.style.display=&#x27;inline-block&#x27;;
10          }
11          phone.οnblur=function(){
12             // 获取文本框的值,value用于获取表单元素的值
13             var phoneVal=this.value;
14             // 判断手机号码是否是11位的纯数字
15             if(phoneVal.length==11 &amp;&amp; isNaN(phoneVal)==false){
16                tip.innerHTML=&#x27;&lt;img src=&quot;img/right.png&quot;&gt;&#x27;;
17             }else{
18              tip.innerHTML=&#x27;&lt;img src=&quot;img/error.png&quot;&gt;&#x27;;
19             }
20          }
21        }
22    &lt;/script&gt;
23    &lt;div class=&quot;box&quot;&gt;
24        &lt;input type=&quot;text&quot; id=&quot;phone&quot; placeholder=&quot;请输入手机号码&quot;&gt;
25        &lt;span class=&quot;tip&quot; id=&quot;tip&quot;&gt;请输入有效的手机号码&lt;/span&gt;
26    &lt;/div&gt;
27

onchange:域的内容改变时发生(一般作用于 select 或 checkbox 复选框或 radio 单选按钮);

案例:皮肤背景色改变。


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
1    &lt;script&gt;
2      window.οnlοad=init;
3      function init(){
4        var menu=document.getElementById(&#x27;menu&#x27;);
5        menu.οnchange=function(){
6          //selectedIndex 属性可设置或返回下拉列表中被选选项的索引号。
7          //语法 selectObject.selectedIndex=number    
8          var bgcolor=menu.options[menu.selectedIndex].value;
9          if(bgcolor==&quot;&quot;){
10            document.body.style.background=&quot;#fff&quot;;
11          }else{
12            document.body.style.background=bgcolor;
13          }
14        }
15      }
16    &lt;/script&gt;
17
18    &lt;div class=&quot;box&quot;&gt;
19        请选择你喜欢的背景色
20        &lt;select id=&quot;menu&quot;&gt;
21          &lt;option value=&quot;&quot;&gt;请选择&lt;/option&gt;
22          &lt;option value=&quot;#f00&quot;&gt;红色&lt;/option&gt;
23          &lt;option value=&quot;#ff0&quot;&gt;黄色&lt;/option&gt;
24          &lt;option value=&quot;#f0f&quot;&gt;紫色&lt;/option&gt;
25        &lt;/select&gt;
26    &lt;/div&gt;
27

onsubmit:表单中的确认按钮被点击时发生(绑定在 form 标签上);


onmousedown:鼠标按钮在元素上按下时触发;

onmousemove:在鼠标指针移动时发生;

onmouseup:在元素上松开鼠标按钮时触发;

案例:多行文本框输入字符计算。


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
1    &lt;style&gt;
2        .text span{font-weight:bold;color:#f00;}
3        em{font-style:normal;}
4        b{color:#666;font-weight: normal;}
5    &lt;/style&gt;
6    &lt;div class=&quot;text&quot;&gt;
7        &lt;b id=&quot;showcount&quot;&gt;你还可以输入&lt;/b&gt;
8        &lt;span id=&quot;totalbox&quot;&gt;&lt;em id=&quot;count&quot;&gt;10&lt;/em&gt;/10&lt;/span&gt;
9    &lt;/div&gt;
10    &lt;textarea name=&quot;&quot; id=&quot;text&quot; cols=&quot;70&quot; rows=&quot;4&quot;&gt;&lt;/textarea&gt;
11    &lt;script&gt;
12      var showcount=document.getElementById(&#x27;showcount&#x27;),
13          totalbox=document.getElementById(&#x27;totalbox&#x27;),
14          count=document.getElementById(&#x27;count&#x27;),
15          text=document.getElementById(&#x27;text&#x27;),
16          total=10;
17      //绑定键盘时间
18      document.οnkeyup=function(){
19        var len=text.value.length;
20        var allow=total-len;
21        var overflow=len-total;
22        if(allow&lt;0){
23          showcount.innerHTML=&#x27;你已超出&#x27;+overflow;
24          totalbox.innerHTML=&#x27;&#x27;;
25        }else{
26          showcount.innerHTML=&#x27;你还可以输入&#x27;;
27          totalbox.innerHTML=&#x27;&lt;em id=&quot;count&quot;&gt;&#x27;+allow+&#x27;&lt;/em&gt;/10&#x27;;
28        }
29      }
30  &lt;/script&gt;
31

onresize:当调整浏览器窗口的大小时触发;

onscroll:拖动滚动条滚动时触发。

案例:判断浏览器窗口和滚动发生变化。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1    &lt;style&gt;
2       .box{width:200px;height:200px;background:#f00;overflow:auto;}
3    &lt;/style&gt;
4    &lt;div class=&quot;box&quot; id=&quot;box&quot;&gt;
5        &lt;p&gt;拖动&lt;/p&gt;
6        &lt;p&gt;拖动&lt;/p&gt;
7        &lt;p&gt;拖动&lt;/p&gt;
8        &lt;p&gt;拖动&lt;/p&gt;
9        &lt;p&gt;拖动&lt;/p&gt;
10    &lt;/div&gt;
11    &lt;script&gt;
12       // 浏览器窗口尺寸发生改变时
13       window.οnresize=function(){
14            console.log(&quot;我的尺寸被改变了&quot;);
15       }
16       // 拖动滚动条
17       window.οnscrοll=function(){
18            console.log(&quot;我被拖动了&quot;);
19       }
20       box.οnscrοll=function(){
21            console.log(&quot;我是DIV的滚动条&quot;);
22       }
23    &lt;/script&gt;
24

案例:按钮的交互变化。 


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
1    &lt;style&gt;
2   #btn{padding: 5px 30px; display: inline-block; color:#fff; border-radius: 5px;}
3       .lock{background: #f0f;}
4       .unlock{background: #f00;}
5    &lt;/style&gt;
6    &lt;div class=&quot;lock&quot; id=&quot;btn&quot;&gt;锁定&lt;/div&gt;
7   &lt;script&gt;
8        // 获取按钮
9        var btn=document.getElementById(&quot;btn&quot;);
10        function clickBtn(){
11           alert(&quot;我是按钮&quot;);
12        }
13        // 点击按钮调用clickBtn这个函数
14        btn.οnclick=clickBtn;
15
16        // 给按钮绑定事件,this是对该DOM元素的引用
17        btn.οnclick=function(){
18           // 判断如果按钮是锁定,则显示为解锁,变为灰色,否则显示为锁定,变为蓝色
19           // 方法一 用类去判断
20           if(this.className==&quot;lock&quot;){
21               this.className=&quot;unlock&quot;;
22               this.innerHTML=&quot;解锁&quot;;
23           }else{
24               this.className=&quot;lock&quot;;
25               this.innerHTML=&quot;锁定&quot;;
26           }
27           // 方法二 用innerHTML中的的内容去判断
28           /*
29           if(this.innerHTML==&quot;锁定&quot;){
30               this.className=&quot;unlock&quot;;
31               this.innerHTML=&quot;解锁&quot;;
32           }else{
33               this.className=&quot;lock&quot;;
34               this.innerHTML=&quot;锁定&quot;;
35           }
36           */
37        }
38  &lt;/script&gt;
39

5、键盘事件与 keyCode 属性

onkeydown:在用户按下一个键盘按键时发生(按下键盘事件);

onkeypress:在键盘按键被按下并释放一个键时发生;

onkeyup:在键盘按键被松开时发生;

keyCode:返回 onkeydown、onkeypress 或 onkeyup 事件触发的键的值的字符代码,或者的键的代码。

说明:event 代表事件的状态,如触发 event 对象的元素、鼠标的位置及状态等。

6、关于 this 指向

在事件触发的函数中,this 是对该 DOM 对象的引用。

 window.onload 页面加载完成后触发的事件。


1
2
3
4
5
6
7
8
9
10
11
1    &lt;script&gt;
2      window.οnlοad=function(){
3        var box=document.getElementById(&#x27;btn&#x27;);
4        var clicked=function(){
5          alert(&#x27;window是一个全局对象&#x27;);
6        }
7        btn.οnclick=clicked;
8      }
9    &lt;/script&gt;
10    &lt;button id=&#x27;btn&#x27;&gt;我是一个按钮&lt;/button&gt;
11

七、BOM基础

window对象、全局对象、window对象的方法 window.alert()、window.confirm()、window.prompt()、window.open()、window.close()。

1、window对象

window 是浏览器的一个实例,在浏览器中,window 对象有双重角色,它既是通过 JavaScript 访问浏览器窗口的一个接口,又是 ECMAScript 规定的 Global 对象。

1.1  全局对象

全局变量/全局方法——脚本的任何一个地方都能调用的变量/方法。

全局函数——window 声明  
window.函数名 = function(){ } 。

所有的全局变量和全局方法都被归在 window 上。

1.2  window 对象的方法

1.2.1   window.alert(“content”)

1)功能:
警告框,带有一段消息和一个确认按钮

2)返回值:点击确定按钮,alert() 返回 undefined

1.2.2   window.confirm(“message”)

1)功能:
提示框,显示一个带有指定消息、取消按钮和确定按钮的提示框

2)返回值:如果用户点击确定按钮,confirm() 返回 true;

                    如果用户点击取消按钮,confirm() 返回 false。

JavaScript基础


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
1&lt;div id=&quot;box&quot;&gt;
2  &lt;span&gt;iphone6s&lt;/span&gt;
3  &lt;input type=&quot;button&quot; value=&quot;删除&quot; id=&quot;btn&quot; /&gt;
4&lt;/div&gt;
5
6&lt;script&gt;
7
8  // 获取按钮,绑定事件
9  var btn = document.getElementById(&quot;btn&quot;),
10      box = document.getElementById(&quot;box&quot;);
11  btn.onclick = function(){
12      // 弹出确认对话框
13      var result = window.confirm(&quot;您确定要删除吗?删除之后该信息\n将不可恢复!&quot;);
14      if(result){
15        box.style.display=&quot;none&quot;;
16      }
17  }
18
19  var age = 15;
20
21  function sayAge(){
22      alert(&#x27;我&#x27; + age);
23  }
24
25  // 全局变量
26  window.username = &quot;marry&quot;;   // var username=&quot;marry&quot;;
27
28  // 全局方法
29  window.sayName = function(){
30      alert(&quot;我是&quot; + this.username);
31  }
32
33  // sayAge();
34  // window.sayName();
35
36  // 弹出输入框
37  var message = prompt(&quot;请输入您的星座&quot;,&quot;天蝎座&quot;);
38  console.log(message);
39
40&lt;/script&gt;
41

1.2.3   window.prompt(“text,defaultText”)

1)语法:
window.prompt(“text,defaultText”)

2)参数说明:

     
text:在对话框中显示的纯文本(而不是HTML格式的文本)

      defaultText:默认输入文本

3)返回值:如果用户点击提示框的取消按钮,则返回null;

                    如果用户点击确认按钮,则返回输入字段当前显示的文本。

注:\n 在 javascript 中实现文字换行。

1.2.4   window.open(pageURL,name,parameters)

1)语法:window.open(pageURL,name,parameters)

2)功能:打开一个新的浏览器窗口或查找一个已命名的窗口

3)参数说明:pageURL 子窗口路径,name 子窗口句柄( name 声明了新窗口的名称,方便后期通过 name 对子窗口进行引用),parameters 窗口参数(各参数用逗号分隔)

1.2.5   window.close( )

1)语法:window.close( )

2)功能:关闭浏览器窗口


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1&lt;input type=&quot;button&quot; value=&quot;退 出&quot; id=&quot;quit&quot; /&gt;
2&lt;script&gt;
3  window.onload = function(){
4    // 打开子窗口,显示newwindow.html
5    window.open(&quot;newwindow.html&quot;,&quot;newwindow&quot;,&quot;width=400,height=200,left=0,top=0,toolbar=no,menubar=no,scrollbars=no,location=no,status=no&quot;);
6    var quit = document.getElementById(&quot;quit&quot;);
7
8    // 点击关闭当前窗口
9    quit.onclick = function(){
10      window.close(&quot;newwindow.html&quot;);
11    }
12  }
13&lt;/script&gt;
14

总结 window 对象的方法:

1、alert 警告框,点击确认返回 undefined;
2、confirm 提示框返回boolean,点击确认返回 true,点击取消返回 false;
3、prompt 对话框,点击确认返回 文本框中输入的内容,点击取消返回 null;
4、window.open('链接','打开窗口名字','打开的窗口参数设置')、window.close()。
5、\n 在 JavaScript 中实现文字换行。

2、定时器

setTimeout() 延时器、clearTimeout() 清除延时器、setInterval() 间歇性调用

2.1  setTimeout 延时器

1)语法:setTimeout(code,millisec)

2)功能:在指定的毫秒数后调用函数或计算表达式

3)参数说明:code 调用的函数或要执行的 JavaScript 代码串,millisec 在执行代码前需等待的毫秒数。

4)说明:setTimeout() 只执行 code 一次。如果要多次调用,使用 setInterval() 或者让 code 自身再次调用 setTimeout()。

                setTimeout() 返回一个 ID 值通过它取消超时调用。

2.2  clearTimeout 清除延时器

1)语法:clearTimeout(id_of_settimeout)

2)功能:取消 setTimeout() 方法设置的 timeout

3)参数说明:id_of_settimeout 由setTimeout() 返回的 ID 值,该值标识要取消的延迟执行代码块。


1
2
3
4
5
6
7
8
9
10
11
12
1//setTimeout(&quot;alert(&#x27;hello&#x27;)&quot;,4000);
2var fnCall = function(){
3  alert(&quot;world&quot;);
4}
5var timeout = setTimeout(function(){
6  alert(&quot;hello&quot;);
7}, 1000)
8
9// clearTimeout(timeout1);
10
11//setTimeout(fnCall,5000);
12

2.3  setInterval 间歇调用 

1)语法:setInterval(code,millisec)

2)功能:每隔指定的时间执行一次代码

3)参数说明:code 要调用的函数或要执行的代码串,millisec 周期性执行或调用 code 之间的时间间隔,以毫秒计。

注:JavaScript 是单线程语言,单线程所执行的代码必须按照顺序。


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
1var intervalId = setInterval(function(){
2                   alert(&quot;您好&quot;);
3                 }, 1000)
4
5// 2秒之后停止弹出对话框
6setTimeout(function(){
7  clearInterval(intervalId);
8}, 2000);
9
10
11var num = 1, max = 10, timer = null;
12// 每隔 1 秒针 num 递增一次,直到 num 的值大于等于 max 清除
13timer = setInterval(function(){
14          console.log(num);
15          num++;
16          if(num &gt;= max){
17            clearInterval(timer);
18          }
19        }, 1000);
20
21
22// 使用超时调用实现
23function inCreamentNum(){
24  console.log(num);   // 1 2 3 10
25  num++;
26  if(num &lt;= max){
27    setTimeout(inCreamentNum, 1000);
28  } else {
29    clearTimeout(timer);
30  }
31}
32timer = setTimeout(inCreamentNum, 1000);
33

3、location对象

location 对象提供了与当前窗口中加载文档有关的信息,还提供了一些导航的功能,它既是 window 对象的属性,也是 document 对象的属性。

3.1  location 对象的常用属性

3.1.1  location.href

1)语法:location.href

2)功能:返回当前加载页面的完整 URL

3)说明:location.href 与 location.location 等价


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1&lt;div class=&quot;box&quot;&gt;
2  请输入搜索关键字:
3  &lt;input type=&quot;text&quot; placeholder=&quot;请输入搜索关键字&quot; id=&quot;key&quot;&gt;
4  &lt;input type=&quot;button&quot; value=&quot;搜索&quot; id=&quot;search&quot;&gt;
5&lt;/div&gt;
6&lt;a href=&quot;#&quot; id=&quot;go&quot;&gt;跳转&lt;/a&gt;
7&lt;script&gt;
8  // 给按钮绑定事件
9  var search = document.getElementById(&quot;search&quot;);
10  search.οnclick=function(){
11    // 获取搜索关键字并对它进行编码
12    var key = encodeURIComponent(document.getElementById(&quot;key&quot;).value);
13    // 跳转到指定页面
14    location.href = &#x27;index9.html?search_key=&#x27; + key;
15  }
16  var sea = &quot;搜索&quot;
17  document.getElementById(&quot;go&quot;).href=&#x27;index.html?key=&#x27; + encodeURI(sea);
18&lt;/script&gt;
19

3.1.2  location.hash

1)语法:location.hash(瞄点链接)

2)功能:返回 URL 中的 hash( #号后跟零或多个字符 ),如果不包含则返回空字符串。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1&lt;style&gt;
2  .box1{height:400px;background:#ccc;}
3  .box2{height:600px;background:#666;}
4&lt;/style&gt;
5&lt;div class=&quot;box1&quot; id=&quot;top&quot;&gt;&lt;/div&gt;
6&lt;div class=&quot;box2&quot;&gt;&lt;/div&gt;
7&lt;input type=&quot;button&quot; id=&quot;btn&quot; value=&quot;返回顶部&quot;&gt;
8&lt;script&gt;
9  // console.log(location.href);
10  // console.log(location.hash);
11  var btn=document.getElementById(&quot;btn&quot;);
12    btn.οnclick=function(){
13    location.hash=&quot;#top&quot;;
14  }
15  console.log(location.pathname);
16&lt;/script&gt;
17

3.1.3  location.host

1)语法:location.host

2)功能:返回服务器名称和端口号(如果有)

3.1.4  location.hostname

1)语法:location.hostname

2)功能:返回不带端口号的服务器名称

3.1.5  location.pathname

5)语法:location.pathname

6)功能:返回 URL 中的目录或文件名

3.1.6  location.port

1)语法:location.port

2)功能:返回 URL 中指定的端口号,如果没有,返回空字符串

3.1.7  location.protocol

3)语法:location.protocol

4)功能:返回页面使用的协议

3.1.8  location.search

5)语法:location.search

6)功能:返回 URL 的查询字符串。这个字符串以问号开头。


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
1&lt;a href=&quot;index10.html&quot;&gt;index10.html&lt;/a&gt;
2&lt;p&gt; 这是index9.html&lt;/p&gt;
3&lt;script&gt;
4  // 解析地址栏中的参数(查询字符串)
5  function getParam(){
6    // 获取参数信息
7    var url=location.search;
8    if(!url)return null;
9    // 将?号却掉
10    url=url.substr(1);
11    // 以&amp;号为分隔符分割url地址
12    var params,param={},arr;
13    params=url.split(&quot;&amp;&quot;);
14    // [&quot;city_id=28&quot;,&quot;city_name=北京&quot;]
15    //console.log(params);
16    // 遍历params这个数组
17    for(var i=0,len=params.length;i&lt;len;i++){
18      arr=params[i].split(&quot;=&quot;);
19      // 将arr[0]作为param这个对象的属性,
20      // 将arr[1]作为param这个对象的属性值
21      param[arr[0]]=decodeURIComponent(arr[1]);
22    }
23    return param;
24  }
25  var params=getParam();
26  console.log(params);
27&lt;/script&gt;
28

3.2   location对象方法

改变浏览器位置的方法:location.href属性,location对象其他属性也可改变URL,location.hash,location.search.

3.2.1  location.replace()

1)语法:location.replace(url)

2)功能:重新定向 URL

3)说明:使用 location.replace 不会在历史记录中生成新纪录。

3.2.2  location.reload()

1)语法:location.reload()

2)功能:重新加载当前显示的页面。

3)说明:location.reload() 有可能从缓存中加载,location.reload(true) 从服务器重新加载。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1&lt;input type=&quot;button&quot; value=&quot;刷新&quot; id=&quot;reload&quot;&gt;
2&lt;script&gt;
3/*
4setTimeout(function(){
5  //location.href=&#x27;index6.html&#x27;;
6  //window.location=&#x27;index6.html&#x27;;
7  location.replace(&quot;index6.html&quot;);
8},1000)
9*/
10document.getElementById(&quot;reload&quot;).οnclick=function(){
11  location.reload(true);
12}
13&lt;/script&gt;
14

4、history对象

history 对象保存了用户在浏览器中访问页面的历史记录。

4.1  history.forward()

1)语法:history.forward()

2)功能:回到历史记录的下一步

3)说明:相当于使用了 history.go(1)

4.2  history.back()

1)语法:history.back()

2)功能:回到历史记录的上一步

3)说明:相当于使用了history.go(-1)

4.3  history.go(-n)

1)语法:history.go(-n)

2)功能:回到历史记录的前 n 步

3)语法:history.go(n)

4)功能:回到历史记录的后 n 步


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
1&lt;p&gt; 这是index11.html&lt;/p&gt;
2&lt;div&gt;&lt;a href=&quot;index12.html&quot;&gt;这是index12.html&lt;/a&gt;&lt;/div&gt;
3&lt;p&gt;&lt;input type=&quot;button&quot; value=&quot;后退&quot; id=&quot;btn&quot;&gt;&lt;/p&gt;
4&lt;p&gt;&lt;input type=&quot;button&quot; value=&quot;前进&quot; id=&quot;btn2&quot;&gt;&lt;/p&gt;
5&lt;p&gt;&lt;input type=&quot;button&quot; value=&quot;前进2&quot; id=&quot;btn3&quot;&gt;&lt;/p&gt;
6&lt;script&gt;
7  var btn = document.getElementById(&quot;btn&quot;);
8  var btn2 = document.getElementById(&quot;btn2&quot;);
9  var btn3 = document.getElementById(&quot;btn3&quot;);
10  // 点击btn按钮时回到历史记录的上一步
11  btn.onclick = function() {
12    // history.back();
13    history.go(-2);
14  }
15  // 点击btn2按钮时回到历史记录的上一步
16  btn2.onclick = function() {
17    // history.forward();
18    history.go(1);
19  }
20  btn3.onclick = function() {
21    // history.forward();
22    history.go(2);
23  }
24&lt;/script&gt;
25

5、Screen 对象及其常用属性

5.1  Screen 对象

Screen 对象包含有关客户端显示屏幕的信息。

5.2  Screen 对象属性

1)screen.availWidth 返回可用的屏幕宽度(获取),screen.availHeight 返回可用的屏幕高度

2)window.innerWidth,window.innerHeight 获取窗口文档显示区的宽和高。


1
2
3
4
5
6
1console.log(&quot;页面宽:&quot;+screen.availWidth);
2console.log(&quot;页面高:&quot;+screen.availHeight);
3
4console.log(&quot;pageWidth:&quot;+window.innerWidth);
5console.log(&quot;pageHeight:&quot;+window.innerHeight);
6

6、Navigator 对象

UserAgent:用来识别浏览器名称、版本、引起以及操作系统等信息的内容。


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
1//console.log(navigator.userAgent);
2// 判断浏览器
3function getBrowser(){
4  var explorer = navigator.userAgent,browser;
5  if(explorer.indexOf(&quot;MSIE&quot;)&gt;-1){
6    browser = &quot;IE&quot;;
7  } else if (explorer.indexOf(&quot;Chrome&quot;)&gt;-1){
8    browser = &quot;Chrome&quot;;
9  } else if (explorer.indexOf(&quot;Opera&quot;)&gt;-1){
10    browser = &quot;Opera&quot;;
11  } else if (explorer.indexOf(&quot;Safari&quot;)&gt;-1){
12    browser = &quot;Safari&quot;;
13  }
14  return browser;
15}
16var browser = getBrowser();
17console.log(&quot;您当前使用的浏览器是:&quot;+browser);
18// 判断终端
19function isPc(){
20  var userAgentInfo = navigator.userAgent,
21      Agents = [&quot;Andriod&quot;,&quot;iPhone&quot;,&quot;symbianOS&quot;,&quot;windows phone&quot;,&quot;iPad&quot;,&quot;iPod&quot;],
22      flag = true, i;
23  console.log(userAgentInfo);
24  for(i=0;i&lt;Agents.length;i++){
25    if(userAgentInfo.indexOf(Agents[i])&gt;-1){
26      flag = false;
27      break;
28    }
29  }
30  return flag;
31}
32var isPcs = isPc();
33console.log(isPcs);
34

案例:验证码发送


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
1&lt;script&gt;
2window.οnlοad=function(){
3  var  btn=document.getElementById(&quot;btn&quot;),
4       times=10,
5       timer=null;
6  btn.οnclick=function(){
7    if(this.getAttribute(&quot;clicked&quot;)){
8      return false;
9    }
10    var _this = this;
11    timer = setInterval(function(){
12      times--;
13      if(times &lt;= 0){
14        clearInterval(timer);
15        _this.value=&quot;发送验证码&quot;;
16        //_this.disabled=false;
17        _this.removeAttribute(&quot;clicked&quot;,false);
18        times=10;
19      } else {
20        _this.value=times+&#x27;秒后重试&#x27;;
21        //_this.disabled=true;
22        _this.setAttribute(&quot;clicked&quot;,true);
23      }
24    }, 1000)
25  }
26}
27&lt;/script&gt;
28

 

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++ explicit关键字

2022-1-11 12:36:11

病毒疫情

福建省新型冠状病毒肺炎疫情情况

2020-8-18 9:35:00

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索