6.javaScirpt—js介绍及ECMAScript的关系

一、javaScript概述

ECMAScript和javaScript的关系是:前者是后者的规格,后者是前者的实现。

文档对象模型(DOM):Doucunment object model(整合js,css,html)

浏览器对象模型(BOM):Broswer object model(整合js和浏览器)

二、js的引入和输出

2.1 js的引入

行内引入

<开始标签 on+事件类型= "js内容" ></结束标签>

这种引入必须结合事件来使用,但是内部js和外部js可以不结合事件。

<body> 
    <input type="button" onclick="alert('行内引入')" value="button" name="button"> 
    <button onclick="alert(123)">按钮</button> 
</body>   

内部引入

在head或body中,定义script标签,然后在script标签里面写js代码。

<script type="text/javascript">
        function clickhandler(){
            alert('好你个头');       
        }
    </script>

外部引入

引入外部js文件

<head>
  <script src=''></script>
</head>

2.2 js输出

//document.write()向文档内输入内容,不会覆盖原文档的内容
document.write('<span class="span1">233<span>')
//console控制台 输出【开发者工具】
console.log('log')   //向控制台抛出一个信息
console.error('错误')   //向控制台抛出一个异常
console.dir(window)    //console.dir()输入一个对象的全部属性
console.clear()     //清除
每个能独立完成一个功能的代码以分号结束,这就是一个代码块
 
alert()  //弹出一个带有一条指定信息的消息
innerHTML/innerText   //获取或者向指定元素内添加内容
innerHTML   //获取元素内所有的内容(包括元素),还可以解析内容的样式
innerText    //获取元素内的文本内容innerText    //获取元素内的文本内容

三、js变量和数据类型

3.1 js中变量

js是松散数据类型,所以js变量中可以存任何数据类型,虽然js也是弱语言类型,但是定义变量使用关键字:var str='字符';

一次定义多个值中间用逗号隔开。

var lst=[],func=function(){},n=9;
var str;
str='hello';
alert(str);

var str='hello';
alert(str);

3.2 js变量命名规范

  1. 严格区分大小写
  2. 命名时可以出现字母、数字、下划线、$,也是不能以数字开头和不能由纯数字组成,也能包含关键字和保留字。
  3. 一般使用驼峰命名法:多个单词组成,第一个单词的首字母小写,剩余单词的的首字母大写。

使用 typeof 变量名; 查看类型。

image-20200717155227226

3.3 数据类型

基本数据类型和引用数据类型。

  1. 基本数据类型指的是简单的数据段,包含数字number、字符串string、布尔、null、undefined。
  2. 引用数据类型指的是有多个值构成的对象,包含对象数据类型(数组array、对象object、正则REGEXP)和函数数据类型(function)。

数值(Number)

js不区分整形和浮点型,只有一种数字类型。统称number类型。

var a = 1.1
var b = 11e1	//110
var c = 11e-1 //1.1

字符串(String)

var str = '12'
console.log(str)
sonsole.log(typeof(str))

布尔(Boolean)

var b = true;

空值(Null和Undefine)

var c = null;
var d;

引用数据类型

Function、Object、Array、String、Date

四、运算符

赋值运算符=,+=,-=,*=,/=,%=

算术运算符+,-,*,/,%取余

自增自减,和c语言一样,a++是先赋值后+1,--同理。

比较运算符:>,<,>=,<=,(等于),=(全等),!=,!==(不等同于,值和类型有一个不相同)

逻辑运算符:&&,||

字符串:字符串拼接和字符串运算,使用加号将两个字符串拼接

var surname='a';
var name = 'n';
var username = surname + name

字符串不能进行加法运算,即使是纯数字组成的字符串,但是可以进行其他运算,js会自动把字符串转换成数字。

var a = '10';
var b = '20';
var c = b-a
var d = a*b

特殊的:

var b = 'one';
var c = 'two';
var ret = b*c;

image-20200717163117675

五、数据类型转换

5.1 数值类型转换字符串类型

//数字类型转换成字符串类型
var a1 = 12;
var a2 = '';
var a3 = a1 + a2
console.log(typeof a3); //string

//强制类型转换String()方法
var str1 = String(a1);
console.log(typeof str1);   // string

// toString()方法
var num = 234;
console.log(num.toString());  

5.2 字符串类型转换成数值类型

//2.将字符串类型转换成数字类型
var stringNum = '123';
var a1 = Number(stringNum);
console.log(num2);
var stringNum2 = '789.456werwrs000';
 
// parseInt() 可以解析一个字符串并且返回一个整数
console.log(parseInt(stringNum));
//parseFloat()
console.log(parseFloat(stringNum2));  //789.456

5.3 任何数据类型都可以转换为boolean类型

var a1 = '123';
console.log(Boolean(b1));  // true
// 非0真1
var a2 = 1;
var a3 = 0;
var a4 = -123;
console.log(Boolean(a2));  //true
console.log(Boolean(a3));  //false
console.log(Boolean(a4));  //true
//无限大
var a5 = Infinity;
console.log(Boolean(a5));  //true
//NaN
var a6 = NaN;
console.log(Boolean(a6));  //false
//undefined
var a7;
console.log(Boolean(a7));  //false
//null
var a8 = null;
console.log(Boolean(a8));  //false

六、数组

内置对象是ECMAScript提供出来的一些对象,比如数组,js中数组的长度和元素类型都是非固定的。

6.1 数组的创建方式

1、直接创建

var array = ['an', 'bn', 'cn']
console.log(array)	//控制台输出(3) ["an", "bn", "cn"]

2、构造函数

var array = new Array();

6.2 数组赋值

var array = [];
array[0] = 123;
array[1] = 'aaa';
array[2] = 'bbb';
console.log(array);  

// 通过下标取到相应的值
console.log(array[2]);   // bbb
console.log(array.length);  // 3

//数组遍历for循环
for(var i=0;i<array.length;i++) {
    console.log(array[i]);
}

6.3 数组常用方法

// 1.数组的合并  concat()
var north = ['北京'];
var south = ['上海'];
 
var newArr = north.concat(south);
console.log(newArr);    // (6) ["北京", "上海"]
 
// 2.将数组转换成字符串
var score = [8,7,6,1,0];
 
// toString() 直接转换为字符串  每个元素之间使用逗号隔开
var str = score.toString();
console.log(str);   // 8,7,6,1,0
 
// join()方法,将数组中的元素使用指定的字符串链接起来,它会形成一个新的字符串
var str2 = score.join('|');
console.log(str2);   // 8|7|6|1|0
 
// 3.查找下标
// indexOf()  正向查找
var index = score.indexOf(88);
console.log(index);   // 输出:1,说明数组是从0开始
// 如果查找的值不再数组中则返回-1
var indexNull = score.indexOf(2);
console.log(indexNull);   // -1
 
// lastindex() s 反向查找
var lastIndex = score.lastIndexOf(88);
console.log(lastIndex);    // 1  (依然是1,依然是从0开始)
 
// 4.数组的排序
var names = ['an', 'bn', 'cn'];
 
// 反转数组
var reverseNames = names.reverse();
console.log(reverseNames); // 
console.log(names);   // 
 
// sort():按照26个英文字母排序数组
var enames = names.sort();
console.log(enames);   
 
// 5.移除元素和添加元素
// shift()移除数组中第一个元素 ,返回的结果是移除的第一个元素,原来数组的第一个元素已被移除
var firstName = names.shift();
console.log(firstName);   // an
console.log(enames);    // 
 
// unshift() 想数组的开头添加一个或多个元素,并返回新的长度。
var lastname = names.unshift();  // 添加为空,但是names中本来就有三个元素
console.log(lastname);   // 3
var lastname = names.unshift("shanshan");
console.log(lastname);   // 4  返回的是新的长度
 
// push()  pop()
// push()  向数组的末尾添加一个或多个元素,并返回新的长度
var newNames = names.push('aaa', 'bbb');
console.log(newNames);   // 6
 
// pop()  删除数组的最后一个元素
var a = names.pop()  // pop 删除最后元素并返回,和python一样

七、String、Number、Date、Math

7.1 字符串

创建

var str = 'hello'

常用属性和方法

//获取长度
str.length
// 转换为大写
var bigStr = str.toUpperCase();
console.log(bigStr);     // HELLO 
// 转换为小写
console.log(bigStr.toLowerCase());   // hello
 
// split()第一个参数是以什么样的字符串进行切割;第二个参数是返回的数组的最大长度
var newArr = str.split(' ',1);
console.log(newArr);  // ["hello"]
var newArr2 = str.split('',3);
console.log(newArr2);  // (3) ["h", "e", "l"]
 
// substring 左闭右开,会返回一个新的字符串
var a = str.substring(2,5);
console.log(a);    // llo

7.2 Number对象

Number对象是原始数据的包装对象。

// toString()将number类型转换成字符串类型
var num = 132.32;
var numStr = num.toString();
console.log(typeof numStr);   // string
 
// toFixed()四舍五入
var num2 = 33.31331341;
var newNum = num2.toFixed(2);
console.log(newNum);  // 33.31

7.3 DAte日期对象

Date 对象用于处理日期和时间。可以通过 new 关键词来定义 Date 对象。Date 对象自动使用当前的日期和时间作为其初始值

// 创建日期对象
var myDate=new Date();
 
// 获取一个月中的某一天
console.log(myDate.getDate());   // 7 (今天是6月7日)
console.log(Date());    // Thu Jun 07 2018 11:58:22 GMT+0800 (CST)
// 获取一年中的某一个月 从 Date 对象返回月份 (0 ~ 11)
// 注意:表示月份的参数介于 0 到 11 W3C Javascript 最新Chm格式手册.chm之间。也就是说,如果希望把月设置为 6 月,则参数应该是 5。
console.log(myDate.getMonth()+1); // 6
 
// getDay()  从 Date 对象返回一周中的某一天 (0 ~ 6)
console.log(myDate.getDay());  // 4 (今天是周四)
// 注意:星期一是"1";星期天是"0"。

7.4 Math对象的使用

Math(算数)对象的作用是:执行常见的算数任务。

var pi_value=Math.PI;
var sqrt_value=Math.sqrt(15);
var x = 1.234;
// 天花板函数  返回值大于等于 x,并且与它最接近的整数
var a = Math.ceil(x);
console.log(a);   // 2
 
// 地板函数, 返回值小于等于 x,且与 x 最接近的整数
var b = Math.floor(x);
console.log(b);   // 1
 
// 求 两个数的最大值和最小值
console.log(Math.max(2,5));  // 5
console.log(Math.min(3,7));  // 3
 
// 经常使用的random 方法可返回介于 0 ~ 1 之间的一个随机数
var ran = Math.random();
console.log(ran);  // 返回值包含0,但是不包含1
 
// 100-200之间的随机数
var c = Math.random()*100 + 100;
console.log(c)   // 137.9650704173937(随机)
 
// min - max 之间的随机数公式:
// min + Math.random()*(max-min)
// 5-15
var d = 5+Math.random()*(15-5);

八、函数

函数是由事件驱动的或者当它被调用时执行的可重复使用的代码块。

8.1 js中的函数

//创建,使用function关键字
function func(){
  alert();
}
//使用函数名调用
func();

也可以这么写

//这里和python类似,函数名也是一种特殊的变量
var func = function(){
  alert();
}
func();

8.2 声明函数的时候带参数

function func(a,b){
  alert(a-b);
}
func(1,1);

8.3 声明函数的时候带有参数且有返回值

function func(a){
  return null;
}
func(1);

九、面向对象

9.1 使用Object或对象字面量创建对象

创建一个名为stu的对象,拥有name和age两个属性。

方式一:

var stu = new Object();
student.name = "an";
student.age = "18";

方式二;

//以键值对的方式创建
var stu = {
  name:"an";
  age:11;
}

方式三:

创建n个对象,方式二的代码重复n次。

//点语法:包括get和set方法
var n = stu.name;
stu.age=88

9.2 工厂模式创建对象

js中没有类的概念,但是可以通过封装上述方式实现。

function student(name, age){
  var obj = new Object();
  obj.name = name;
  obj.name = age;
  return obj;
}

var stu1 = student('an', 11);

9.3 构造函数创建对象

Object()构造函数,首字母大写。

var obj = new Object();
obj.name = 'an';

构造函数和普通函数:

  1. 构造函数的创建语法其实在js中并不存在,只是这类函数的调用方法和普通方法不同,构造函数使用new调用,但是普通函数不用。

  2. 构造函数的首字母习惯大写,普通函数小写,用于区分。

  3. 构造函数调用时,会经历 创建一个新的对象——>将构造函数的作用域赋给新对象——>执行构造函数——>返回新的对象。

var Stu = function () {
    this.name = 'an';
    this.age = 11;
    this.fav = function () {
        console.log('按摩')
    }
}
 
// 创建这个对象
var s = new Stu();
console.log(s);    // Stu {name: "an", age: 11, fav: ƒ}
 
var s1 = new Stu();
console.log(s1);		// Stu {name: "an", age: 11, fav: ƒ}

这种方法每次new一个新对象,成员变量和方法都一样。

创建构造函数的方式:

//方式一
function Student() {
    this.name = 'bn';
    this.age = 12;
    this.fav = function () {
        console.log(this.age)
    }
}
var a = new Student();
a.fav();   // 输出:12
 
//方式二:
function Student2() {
    this.name = "cn";
    this.age = 13;
}
Student2.prototype.showname = function () {
    alert(this.name);
}
// 可以在外部任意添加新的方法,不用把所有的方法写在函数中
Student2.prototype.showage = function () {
    alert(this.age);
}
var b = new Student2()
b.showname()

9.4 原型模式创建对象

function Student() {
    this.name = 'an';
    this.age = 20;
}
 
 
Student.prototype.alertName = function(){
                                alert(this.name);
                              };
 
var stu1 = new Student();
var stu2 = new Student();
 
stu1.alertName();  //an
stu2.alertName();  //an
 
alert(stu1.alertName == stu2.alertName);  //true 二者共享同一函数 

十、定时器

10.1 selnterval()

在指定时间为周期循环执行。

// 刷新时间单位为毫秒
var n=0;
var time = null;
time = setInterval(function(){
  n++;
  console.log(n);
}, 100)

10.2 setTimeout()

只在指定时间后执行一次。

setTimeout(function () {
    console.log(time);   // 1
    clearInterval(time);   // 结束定时器
}, 7000);
 
 
//定时器 异步运行 
function hello(){ 
alert("hello"); 
} 
//使用方法名字执行方法 
var t1 = window.setTimeout(hello,1000); 
var t2 = window.setTimeout("hello()",4000);//使用字符串执行方法 
window.clearTimeout(t1);//去掉定时器 

十一、正则表达式

正则:对象RegExp

11.1 创建正则表达式

//1. 构造函数创建  new RegExp("检测文本","修饰符")
//参数1  正则表达式(不能有空格)
//参数2  匹配模式:常用g(全局匹配;找到所有匹配,而不是第一个匹配后停止)和i(忽略大小写吧)
var str = 'luffy 2018';
var reg1 = new RegExp('l','ig');
console.log(reg1);   // 输出:/l/gi
 
//2. 字面量方式创建
var reg2 = /y/ig;    // 检测字符y,不区分大小写,全局匹配

11.2 正则对象提供的检索方式

//正则对象提供的检索方式
//1.test() 检测字符串中是否包含定义字符模式,返回布尔
//要检索的字符在字符串str中 返回true
// console.log(reg2.test(str));  // true
 
//2.exec()方法就是用来检索字符串中正则表达式的匹配
// 如果匹配到了就返回一个存放有结果的数组,如果没有匹配到就返回一个null
console.log(reg2.lastIndex);  // 0 保存一次匹配时开始的下标
console.log(reg2.exec(str));  // ["y", index: 4, input: "luffy 2018", groups: undefined]
console.log(reg2.lastIndex);  // 5

11.3 常用的方法

//match  字符串.match(正则)
var str = "hello world";
var reg3 = /o/g;
// 使用正则表达式模式对字符串执行查找,并将包含查找的结果作为数组返回
console.log(str.match(reg3));    // (2) ["o", "o"]
 
//replace替换: str.replace(被替换的,替换的)
console.log(str.replace(reg3,'*'));   // hell* w*rld
 
//search()  查询字符串在字符中出现的位置 下标
console.log(str.search(reg3));  // 4
 
//split()  以匹配的规则分割
console.log(str.split(reg3));  // (3) ["hell", " w", "rd"]

十二、正则表达式——元字符

12.1 单个字符和数字

//1   . 匹配除换行符(\n)以外的任意字符
var str = "luffyCity 2018";
var reg = /./g;
console.log(reg.exec(str));  // ["l", index: 0, input: "luffyCity 2018", groups: undefined]
 
// \.表示转义匹配.
var str = "www.baidu.com";
var reg = /www\......\.com/g;   //如果想不让字符有其他意义  转义\
console.log(reg.exec(str));  // ["www.baidu.com", index: 0, input: "www.baidu.com", groups: undefined]
 
//2.[]  匹配[]里面的任意一个字符
var str1 = "4awebadsads";
var reg1 = /[a-zA-Z0-9]/g; // 匹配字母还是数字
console.log(reg1.exec(str1));  // ["4", index: 0, input: "4awebadsads", groups: undefined]
 
var str2 = "1s334";
var reg2 = /[0-9][0-9][0-9]/g;  // 匹配多个字符
console.log(reg2.exec(str2));  // ["334", index: 2, input: "1s334", groups: undefined]
 
//3.[^] 所有不在这个范围内的字符
var str3 = "abd123";
var reg3 = /[^a-z][^A-Z]/g;  //匹配除小写字母以外的任意字符
console.log(reg3.exec(str3));  //["12", index: 3, input: "abd123", groups: undefined]
 
//4.\d:匹配数字   对立  \D:匹配非数字
var str4 = "web";
var reg4 = /\d/g;   //匹配数字
var reg5 = /\D/g;   //非数字
console.log(reg4.exec(str4));  //null
console.log(reg5.exec(str4));  //w
 
//5.\w:匹配数字、字母、下划线   \W:匹配除数字、字母、下划线以外的任意字符
var reg6 = /\w/g;  //匹配数字 字母  下划线_
var reg7 = /\W/g;  //匹配除数字 字母  下划线以外的任意字符
console.log(reg6.exec(str4));   //w
console.log(reg7.exec(str4));   //null
 
//6.\s:匹配空格    trim():去除字符串空白
var str5 = " luffy";
var reg8 = /\s/g; //空格
var reg9 = /\S/g; //非空白字符
console.log(reg8.exec(str5));   //" "
console.log(reg9.exec(str5));   //l
 
//7.锚字符  ^以什么开头     $以什么结尾
var str6 = "www.luffy.com";
var reg10 = /^www/g;  // ^字符
console.log(reg10.exec(str6));  // www
 
var reg11 = /www\......\.com$/g;   //字符$
console.log(reg11.exec(str6));  // www.luffy.com
 
var reg12 = /www\...\.com$/g;
console.log(reg12.exec(str6));  // null

12.2 重复的字符

//1. ?  匹配前面的字符0个或一个 ,
var strs = "123webr44546ere";
var reg12 = /[0-9]?/g;
console.log(reg12.exec(strs));   // '1'
 
//2. *  匹配0个或任意多个字符    尽可能多的匹配
var reg13 = /[a-z]*/g; //匹配小写字母,0个或多个
console.log(reg13.exec(strs));  // ""   匹配了0个小写字符
 
//3. + 至少匹配一次
var reg14 = /\d+/g; // 匹配数字
console.log(reg14.exec(strs));  // "123"
 
//4. {10}:匹配连续的10个字符
var stra = "11274567800";
// 以1开头后面连续匹配9个数字结尾
var rega = /^1\d{10}$/g; //以1开头,匹配连续的十个数字
console.log(rega.exec(stra));  // "11274567800"
 
//5. {min,max} 最少min个最多max个
var strb = "edg";
// 以大小写英文字母结尾开头并且最少2个最多3个字母结尾
var regb = /^[a-zA-z]{2,3}$/g;
console.log(regb.exec(strb));  // "edg"
 
//6. |:竖线  或者
var strc = "www.google"; //baidu  google   ujiuye
var regc = /www.baidu|google|ujiuye/g;
console.log(regc.exec(strc));  // "google"
 
//7. ():分组
var strc1 = "www.google"; //baidu  google   ujiuye
var regc1 = /(baidu)|(google)|(ujiuye)/g;
console.log(regc1.exec(strc1));
/*
(4) ["google", undefined, "google", undefined, index: 4, input: "www.google", groups: undefined]
0:"google"  匹配对的字符串
1:undefined  匹配不到
2:"google"
3:undefined
groups:undefined
index:4
input:"www.google"
*/
 
//获取匹配的字符串
console.log(RegExp.$1);
console.log(RegExp.$2);  // google
console.log(RegExp.$3);
 
var str = "helloworld";
var reg = /(hello)(world)/g;
console.log(reg.exec(str));  // (3) ["helloworld", "hello", "world", index: 0, input: "helloworld", groups: undefined]
console.log(RegExp.$1);  // hello
// 将分组好的匹配,调换顺序
console.log(str.replace(reg,"$2 $1"));   // world hello
posted @ 2020-08-08 19:32  journeyerxxx  阅读(155)  评论(0编辑  收藏  举报
返回顶部