文章目录
ECMAScript系列:简介
ECMA(European Computer Manufacturers Association)中文名称为欧洲计算机制
造商协会,这个组织的目标是评估、开发和认可电信和计算机标准。1994 年后该
组织改名为 Ecma 国际。
ECMAScript 是由 Ecma 国际通过 ECMA-262 标准化的脚本程序设计语言。
Ecma 国际制定了许多标准,而 ECMA-262 只是其中的一个,所有标准列表查看
http://www.ecma-international.org/publications/standards/Standard.htm
http://kangax.github.io/compat-table/es6/可查看兼容性
ECMAScript系列:ES6新特性
let 关键字
let 关键字用来声明变量,使用 let 声明的变量有几个特点:
-
不允许重复声明
-
块儿级作用域
-
不存在变量提升
-
不影响作用域链
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>01-let</title>
</head>
<body>
<script>
//声明变量
let a;
let b, c, d;
let e = 100;
let f = 521, g = 'iloveyou', h = [];
//1.变量名不能重复声明
let star = '罗志祥';
//let star='小猪'; //Uncaught SyntaxError: Identifier 'star' has already been declared
//2.块级作用域 es5:全局,函数,eval
{
let gril = '周扬青';
}
//console.log(girl); Uncaught ReferenceError: girl is not defined
//3.不存在变量提升
//console.log(song); Uncaught ReferenceError: Cannot access 'song' before initialization
let song = '恋爱达人';
//4.不影响作用域链
{
let school = '清华';
function fn() {
console.log(school);
}
fn();
}
</script>
</body>
</html>
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.item {
border: 1px solid blue;
width: 100px;
height: 50px;
margin: 10px;
float: left;
}
</style>
</head>
<body>
<div class="container">
<h2 class="page-header">点击切换颜色</h2>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<script>
//获取div元素对象
let items = document.getElementsByClassName('item');
//遍历并绑定事件
for (let index = 0; index < items.length; index++) {
const element = items[index];
element.onclick = function () {
//修改当前元素的背景颜色
element.style.background = 'pink';
}
}
</script>
</body>
</html>
const 关键字
const 关键字用来声明常量,const 声明有以下特点
-
声明必须赋初始值
-
标识符一般为大写
-
不允许重复声明
-
值不允许修改
-
块儿级作用域
**注意:**对象属性修改和数组元素变化不会出发const
错误
**应用场景:**声明对象类型使用const
,非对象类型声明选择let
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>03-const</title>
</head>
<body>
<script>
//声明常量
const SCHOOL = '清华';
//1.一定要赋初始值
//const A;//Uncaught SyntaxError: Missing initializer in const declaration
//2.一般常量使用大写(潜规则)
const a = 100;
//3.常量的值不能修改
//SCHOOL='QINGHUA'; //03-const.html:19 Uncaught TypeError: Assignment to constant variable.
//4.块级作用域
{
const PLAYER = 'UZI';
}
//console.log(PLAYER);//Uncaught ReferenceError: PLAYER is not defined
//5.对于数组合对象的元素修改,不算做对常量的修改,不会报错
const TEAM = ["UZI", "MXLG", "Ming"];
TEAM.push('Meiko');
console.log(TEAM);
</script>
</body>
</html>
变量的解构赋值
ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构赋值。
注意:频繁使用对象方法、数组元素,就可以使用解构赋值形式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>04-解构赋值</title>
</head>
<body>
<script>
//es6 允许按照一定的模式从数组和对象中提取值,对变量进行赋值。被称之为解构赋值
//1.数组的结构
const F4 = ['小沈阳', '刘能', '赵四', '宋小宝'];
let [xiao, liu, zhao, song] = F4;
console.log(xiao); //小沈阳
console.log(liu);//刘能
console.log(zhao);//赵四
console.log(song);//宋小宝
//对象的解构
const zhaobenshan = {
name: '赵本山',
age: '不详',
xiaopin: function () {
console.log('我可以演小品');
}
};
let { name, age, xiaopin } = zhaobenshan;
console.log(name);//赵本山
console.log(age);//不详
console.log(xiaopin);//f(){...}
</script>
</body>
</html>
模板字符串
模板字符串(template string)是增强版的字符串,用反引号(`)标识,特点:
-
字符串中可以出现换行符
-
可以使用 ${xxx} 形式输出变量
注意:当遇到字符串与变量拼接的情况使用模板字符串
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>05-模板字符串</title>
</head>
<body>
<script>
//ES6引入新的声明字符串的方式 反引号【``】 '' ""
//1.声明
const str = `我是一个字符串`;
console.log(str, typeof str);//我是一个字符串 string
//2.内容中可以直接出现换行符
const str1 = `<ul>
<li>沈腾</li>
<li>玛丽</li>
</ul>`;
console.log(str1);
//3.变量拼接
let lovest = '肖战';
let out = `${lovest}是个很酷的演员`;
console.log(out);
</script>
</body>
</html>
简化对象写法
ES6 允许在大括号里面,直接写入变量和函数,作为对象的属性和方法。这样的书写更加简洁。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>06-简化对象写法</title>
</head>
<body>
<script>
//ES6 允许在大括号里面,直接写入变量和函数,作为对象的属性和方法。这样的书写更加简洁
let name = '清华';
let change = function () {
console.log('i can change you.');
}
const school = {
name, change, improve() {
console.log('函数省略function');
}
};
console.log(school);
/*
change: ƒ ()
improve: ƒ improve()
name: "清华"
*/
</script>
</body>
</html>
箭头函数
箭头函数的注意点:
-
如果形参只有一个,则小括号可以省略
-
函数体如果只有一条语句,则花括号可以省略,函数的返回值为该条语句的执行结果
-
箭头函数 this 指向声明时所在作用域下 this 的值
-
箭头函数不能作为构造函数实例化
-
不能使用 arguments
注意:箭头函数不会更改this指向,用来指定回调函数会非常合适
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>07-箭头函数</title>
</head>
<body>
<script>
//ES6 允许使用[箭头](=>)定义函数
//声明一个函数
let fn = function () {
}
let fn1 = (a, b) => {
return a + b;
}
//调用函数
let result = fn1(1, 2);
console.log(result);
//1.this 是静态的. this始终指向函数声明时所在作用域下的 this 的值
function getName() {
console.log(this.name);
}
let getName1 = () => {
console.log(this.name);
}
//设置 window 对象的 name 属性
window.name = '清华';
const school = { name: 'qinghua' };
//直接调用
getName(); //清华
getName1(); //清华
//call 方法调用
getName.call(school); //qinghua
getName1.call(school); //清华
//2.不能作为构造函数实例化对象
// let Person = (name, age) => {
// this.name = name;
// this.age = age;
// }
//let me = new Person('xiao', 30);
//console.log(me);//Uncaught TypeError: Person is not a constructor
//3.不能使用 arguments 变量
// let func = () => {
// console.log(arguments);
// }
//func();//Uncaught ReferenceError: arguments is not defined
//4.箭头函数的简写
//1)省略小括号,当形参有且只有一个的时候
let add = n => {
return n + n;
}
console.log(add(9)); //18
//2)省略花括号,当代码体只有一条语句的时候,此时 return 必须省略
//而且语句的执行结果就是函数的返回值
let pow = n => n * n;
console.log(pow(9));//81
</script>
</body>
</html>
案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>08-箭头函数实践</title>
<style>
div {
width: 200px;
height: 200px;
background: #580;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
//需求1:点击div 2s后改变颜色
let box = document.getElementById('box');
// box.addEventListener('click', function () {
// //保存 this 的值;
// let _this = this;
// //定时器
// setTimeout(function () {
// //修改背景颜色 this
// _this.style.background = 'red';
// }, 2000)
// })
box.addEventListener('click', function () {
setTimeout(() => {
this.style.background = 'red';
})
})
//需求2:从数组中返回偶数的元素
const arr = [1, 6, 9, 10, 100, 25];
// const result = arr.filter(function (item) {
// if (item % 2 == 0) {
// return true;
// }
// else {
// return false;
// }
// })
console.log(result);//[6, 10, 100]
// const result = arr.filter(item => {
// if (item % 2 == 0) return true;
// else return false;
// })
const result = arr.filter(item => item % 2 === 0);
//箭头函数适合于与 this 无关的回调. 定时器,数组的方法回调
//箭头函数不适合与 this 有关的回调. 比如事件回调,对象的方法
</script>
</body>
</html>
参数默认值
ES6 允许给函数参数赋初始值
1)形参初始值 具有默认值的参数,一般位置要靠后(潜规则)
2)与解构赋值结合
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>09-参数默认值</title>
</head>
<body>
<script>
//ES6 允许给函数参数赋初始值
//1.形参初始值 具有默认值的参数,一般位置要靠后(潜规则)
function add(a, b, c = 10) {
return a + b + c;
}
let result = add(1, 2);
console.log(result); //13 //如果没有赋初始值NaN
//2.与解构赋值结合
function connect({ host = '127.0.0.1', username, password, port }) {
console.log(host);
console.log(username);
console.log(password);
console.log(port);
}
connect({ host: 'localhost', username: 'root', password: 'root', port: 3306 });
</script>
</body>
</html>
rest 参数
ES6 引入 rest 参数,用于获取函数的实参,用来代替 arguments
注意:rest 参数非常适合不定个数参数函数的场景
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>10-rest参数</title>
</head>
<body>
<script>
//ES6 引入 rest 参数. 用于获取参数的实参,用来代替 arguments
//ES5 获取实参的方式
function date() {
console.log(arguments);
}
date(1, 2, 3);
/*
0: 1
1: 2
2: 3
callee: ƒ date()
length: 3
Symbol(Symbol.iterator): ƒ values()
__proto__: Object
*/
//rest 参数
function date1(...args) {
console.log(args);
}
date1(1, 2, 3); //[1, 2, 3]
//rest 参数必须要放在参数最后
function fn(a, b, ...args) {
console.log(a);
console.log(b);
console.log(args);
}
fn(1,2,3,4,5,6); //1 2 [3, 4, 5, 6]
</script>
</body>
</html>
spread扩展运算符
扩展运算符(spread)也是三个点(…)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列,对数组进行解包。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>11-spread扩展运算符</title>
</head>
<body>
<script>
//【...】 扩展运算符能将【数组】转换为逗号分隔的【参数序列】
//声明一个数组
const tfboys = ['易烊千玺', '王源', '王俊凯'];
//声明一个函数
function chunwan() {
console.log(arguments);
}
chunwan(...tfboys);//chunwan('易烊千玺','王源','王俊凯')
</script>
</body>
</html>
扩展运算符应用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>12-扩展运算符应用</title>
</head>
<body>
<div></div>
<div></div>
<div></div>
<script>
//1.数组的合并
const kuaizi = ['王太利', '肖央'];
const fenghuang = ['曾毅', '玲花'];
//const zuixuanxiaopingguo = kuaizi.concat(fenghuang);
const zuixuanxiaopingguo=[...kuaizi,...fenghuang];
console.log(zuixuanxiaopingguo); //['王太利', '肖央','曾毅', '玲花']
//2.数组的克隆
const sanzhihua=['E','G','M'];
const sanyecao=[...sanzhihua];
console.log(sanyecao); //['E','G','M']
//3.将伪数组转为真正的数组
const divs=document.getElementsByTagName('div');
console.log(divs); //HTMLCollection(3) [div, div, div]
const divArr=[...divs];
console.log(divArr); //[div, div, div]
</script>
</body>
</html>
Symbol
ES6 引入了一种新的原始数据类型 Symbol,表示独一无二的值。它是
JavaScript 语言的第七种数据类型,是一种类似于字符串的数据类型。
Symbol 特点
-
Symbol 的值是唯一的,用来解决命名冲突的问题
-
Symbol 值不能与其他数据进行运算
-
Symbol 定义 的 对象属 性 不能 使 用 for…in 循 环遍 历 ,但 是可 以 使 用Reflect.ownKeys 来获取对象的所有键名
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>13-symbol</title>
</head>
<body>
<script>
//创建symbol
let s = Symbol();
console.log(s, typeof s); //Symbol() "symbol"
let s2 = Symbol('清华');
let s3 = Symbol('清华');
console.log(s2 === s3); //false
let s4 = Symbol.for('清华');
console.log(s4, typeof s4);//Symbol(清华) "symbol"
let s5 = Symbol.for('清华');
console.log(s4 === s5); //true
//不能与其他数据进行运算
//let result = s + 100; //Cannot convert a Symbol value to a number
//let result=s>100; //Cannot convert a Symbol value to ...
//let result=s+s; //Cannot convert a Symbol value to a ...
</script>
</body>
</html>
symbol创建对象属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>14-symbol创建对象属性</title>
</head>
<body>
<script>
//向对象中添加方法 up down
let game = {
up(){
},
name:'俄罗斯方块'
}
let methods = {
up: Symbol(),
down: Symbol()
}
game[methods.up] = function () {
console.log("我可以改变形状.");
}
game[methods.down] = function () {
console.log("我可以快速下降.");
}
console.log(game);
/*
name: "俄罗斯方块"
up: ƒ up()
Symbol(): ƒ ()
Symbol(): ƒ ()
__proto__: Object
*/
let youxi={
name:'狼人杀',
[Symbol('say')](){
console.log('我可以发言');
},
[Symbol('see')](){
console.log('我可以看见');
}
}
console.log(youxi);
/*
name: "狼人杀"
Symbol(say): ƒ [Symbol('say')]()
Symbol(see): ƒ [Symbol('see')]()
*/
</script>
</body>
</html>
除了定义自己使用的 Symbol 值以外,ES6 还提供了 11 个内置的 Symbol 值,指向语言内部使用的方法。可以称这些方法为魔术方法,因为它们会在特定的场景下自动执行。
内置值 | 说明 |
---|---|
Symbol.hasInstance | 当其他对象使用 instanceof 运算符,判断是否为该对象的实例时,会调用这个方法 |
Symbol.isConcatSpreadable | 对象的 Symbol.isConcatSpreadable 属性等于的是一个布尔值,表示该对象用于 Array.prototype.concat()时,是否可以展开。 |
Symbol.species | 创建衍生对象时,会使用该属性 |
Symbol.match | 当执行 str.match(myObject) 时,如果该属性存在,会调用它,返回该方法的返回值。 |
Symbol.replace | 当该对象被 str.replace(myObject)方法调用时,会返回该方法的返回值。 |
Symbol.search | 当该对象被 str.search (myObject)方法调用时,会返回该方法的返回值。 |
Symbol.split | 当该对象被 str.split(myObject)方法调用时,会返回该方法的返回值。 |
Symbol.iterator | 对象进行 for…of 循环时,会调用 Symbol.iterator 方法,返回该对象的默认遍历器 |
Symbol.toPrimitive | 该对象被转为原始类型的值时,会调用这个方法,返回该对象对应的原始类型值。 |
Symbol. toStringTag | 在该对象上面调用 toString 方法时,返回该方法的返回值 |
Symbol. unscopables | 该对象指定了使用 with 关键字时,哪些属性会被 with环境排除。 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>15-symbol内置属性</title>
</head>
<body>
<script>
class Person {
static [Symbol.hasInstance](param) {
console.log(param); //{ name:'李四'}
console.log('我被用来检测类型了');
}
}
let o = { name: '李四' };
console.log(o instanceof Person); //false
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
arr2[Symbol.isConcatSpreadable] = false;
console.log(arr1.concat(arr2));//[1, 2, 3, [4, 5, 6]]
</script>
</body>
</html>
迭代器
遍历器(Iterator)就是一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署 Iterator 接口,就可以完成遍历操作。
1) ES6 创造了一种新的遍历命令 for…of 循环,Iterator 接口主要供 for…of 消费
2) 原生具备 iterator 接口的数据(可用 for of 遍历)
a) Array
b) Arguments
c) Set
d) Map
e) String
f) TypedArray
g) NodeList
3) 工作原理
a) 创建一个指针对象,指向当前数据结构的起始位置
b) 第一次调用对象的 next 方法,指针自动指向数据结构的第一个成员
c) 接下来不断调用 next 方法,指针一直往后移动,直到指向最后一个成员
d) 每调用 next 方法返回一个包含 value 和 done 属性的对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>16-迭代器</title>
</head>
<body>
<script>
//声明一个数组
const xiyou = ['唐僧', '孙悟空', '猪八戒', '沙僧'];
//使用for...of 遍历数组
for (let v of xiyou) {
console.log(v);
}
console.log(xiyou); // ["唐僧", "孙悟空", "猪八戒", "沙僧"]
let iterator = xiyou[Symbol.iterator]();
//调用对象的next方法
console.log(iterator.next()); //{value: "唐僧", done: false}
console.log(iterator.next()); //{value: "孙悟空", done: false}
console.log(iterator.next()); //{value: "猪八戒", done: false}
console.log(iterator.next()); //{value: "沙僧", done: false}
console.log(iterator.next()); //{value: undefined, done: true}
</script>
</body>
</html>
迭代器应用案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>17-迭代器自定义遍历对象</title>
</head>
<body>
<script>
//声明一个对象
const banji = {
name: '尖子班',
stus: [
'zhangsan',
'lisi',
'wangwu',
'zhaoliu'
],
[Symbol.iterator]() {
let index = 0;
let _this = this;
return {
next: function () {
if (index < _this.stus.length) {
const result = { value: _this.stus[index], done: false };
index++;
return result;
}
else return { value: undefined, done: true };
}
}
}
}
//遍历这个对象
for (let v of banji) { //Uncaught TypeError: banji is not iterable
console.log(v); //
}
</script>
</body>
</html>
生成器
生成器函数是 ES6 提供的一种异步编程解决方案,语法行为与传统函数完全不同
代码说明:
-
- 的位置没有限制
-
生成器函数返回的结果是迭代器对象,调用迭代器对象的 next 方法可以得到
yield 语句后的值
- yield 相当于函数的暂停标记,也可以认为是函数的分隔符,每调用一次 next
方法,执行一段代码
- next 方法可以传递实参,作为 yield 语句的返回值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>18-生成器</title>
</head>
<body>
<script>
//生成器其实就是一个特殊的函数
//异步编程 纯回调函数
//yield 函数代码的分隔符
function* gen() {
//console.log(111);
yield '一只没有耳朵';
//console.log(222);
yield '一只没有尾巴';
//console.log(333);
yield '真奇怪';
//console.log(444);
}
let iterator = gen();
//console.log(iterator); /*gen object*/
console.log(iterator.next()); //{value: "一只没有耳朵", done: false}
console.log(iterator.next()); //{value: "一只没有尾巴", done: false}
console.log(iterator.next()); //{value: "真奇怪", done: false}
console.log(iterator.next()); //{value: undefined, done: true}
for(let v of gen()){
console.log(v);
}
</script>
</body>
</html>
生成器函数参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>19-生成器函数参数</title>
</head>
<body>
<script>
function * gen(arg){
console.log(arg);//param1
let one =yield 111;
console.log(one); //param2
let two=yield 222;
console.log(two); //param3
let three=yield 333;
console.log(three); //param4
}
//执行获取迭代器对象
let iterator=gen('param1');
//next方法可以传入实参
console.log(iterator.next()); //{value: 111, done: false}
console.log(iterator.next('param2')); //{value: 222, done: false}
console.log(iterator.next('param3')); //{value: 333, done: false}
console.log(iterator.next('param4')); //{value: undefined, done: true}
</script>
</body>
</html>
生成器函数实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>20-生成器函数实例</title>
</head>
<body>
<script>
//异步编程 js本身是异步单线程 文件操作 网络操作
//1s 后控制台输出111 2s 后输出222 3s 后输出333
//回调地狱
// setTimeout(() => {
// console.log(111);
// setTimeout(() => {
// console.log(222);
// setTimeout(() => {
// console.log(333);
// }, 3000)
// }, 2000);
// }, 1000);
function one() {
setTimeout(() => {
console.log(111);
iterator.next();
}, 1000);
}
function two() {
setTimeout(() => {
console.log(222);
iterator.next();
}, 2000);
}
function three() {
setTimeout(() => {
console.log(333);
iterator.next();
}, 3000);
}
function* gen() {
yield one();
yield two();
yield three();
}
let iterator = gen();
iterator.next();
</script>
</body>
</html>
生成器函数实例2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>21-生成器函数实例2</title>
</head>
<body>
<script>
//模拟获取 用户数据 订单数据 商品数据
function getUsers() {
setTimeout(() => {
let data = '用户数据';
//调用next方法,并且将数据传入
iterator.next(data);
}, 1000)
}
function getOrders() {
setTimeout(() => {
let data = '订单数据';
iterator.next(data);
}, 1000)
}
function getGoods() {
setTimeout(() => {
let data = '商品数据';
iterator.next(data);
}, 1000)
}
function * gen() {
let users = yield getUsers();
console.log(users);
let orders = yield getOrders();
console.log(orders);
let goods = yield getGoods();
console.log(goods);
}
let iterator = gen();
iterator.next();
</script>
</body>
</html>
Promise
Promise 是 ES6 引入的异步编程的新解决方案。语法上 Promise 是一个构造函数,
用来封装异步操作并可以获取其成功或失败的结果。
-
Promise 构造函数: Promise (excutor) {}
-
Promise.prototype.then 方法
-
Promise.prototype.catch 方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>22-promise基本语法</title>
</head>
<body>
<script>
//实例化 Promise 对象
const p = new Promise(function (resolve, reject) {
setTimeout(function () {
// let data = '数据库中的用户数据';
// resolve(data);
let err = '数据读取失败';
reject(err);
}, 1000);
})
//调用 Promise 对象的 then方法
p.then(function (value) {
console.log(value); //数据库中的用户数据
}, function (reason) {
console.log(reason);
})
</script>
</body>
</html>
Promise读取文件案例
// //1.引入fs模块
const fs = require('fs');
// //2.调用方法读取文件
// fs.readFile('./01-let.html',(err,data)=>{
// //如果失败,则抛出错误
// if(err) throw err;
// //如果没有出错,则输出内容
// console.log(data.toString());
// })
//3.使用 Promise 封装
const p = new Promise((resolve, reject) => {
fs.readFile('./01-let.htm', (err, data) => {
//判断如果失败
if (err) reject(err);
//如果成功
resolve(data);
})
})
p.then(value => {
console.log(value.toString());
}, reason => {
console.log(reason);
})
Promise封装ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>promise封装ajax</title>
</head>
<body>
<script>
const p = new Promise(function (resolve, reject) {
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化
xhr.open("GET", "https://api.apiopen.top/getJoke");
//3.发送
xhr.send();
//4.绑定事件,处理响应结果
xhr.onreadystatechange = function () {
//判断
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
}
else reject(xhr.response);
}
}
})
//指定回调
p.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err);
});
</script>
</body>
</html>
Promise.prototype.then方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>25-Promise.prototype.then</title>
</head>
<body>
<script>
//创建 promise 对象
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('用户数据');
}, 1000)
})
//调用 then 方法 then方法的返回结果是 promise 对象,对象状态由回调函数执行结果决定
//1.如果回调函数中返回的结果是 非 promise 类型的属性,状态为成功,返回值为对象的成功的值
const result = p.then(value => {
console.log(value);
//1.非 promise 类型的属性
//return 123; ///*[[PromiseState]]: "fulfilled" [[PromiseResult]]:123*/
//2.是 promise 对象
// return new Promise((resolve,reject)=>{
// //resolve('ok'); /*[[PromiseState]]: "fulfilled" [[PromiseResult]]: "ok"*/
// reject('error'); /* [[PromiseState]]: "rejected" [[PromiseResult]]: "error"*/
// })
throw new Error('error.');/*[[PromiseState]]: "rejected" [[PromiseResult]]: Error: error. at*/
}, reason => {
console.warn(reason);
})
console.log(result);
//链式调用
p.then(value=>{
}).then(value=>{
});
</script>
</body>
</html>
Promise.catch方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>26-promise-catch方法</title>
</head>
<body>
<script>
const p =new Promise((resolve,reject)=>{
setTimeout(()=>{
//设置 p 对象的状态为失败,并设置失败的值
reject("error");
},1000)
})
p.then(value=>{
},reason=>{
console.warn(reason);
})
p.catch(reason=>{
console.warn(reason);
})
</script>
</body>
</html>
promise读取多个文件
//引入 fs 模块
const fs = require('fs');
// fs.readFile('./01-let.html', (err, data1) => {
// fs.readFile('./02-let实践案例.html', (err, data2) => {
// fs.readFile('./03-const.html', (err, data3) => {
// let result=data1+'\r\n'+data2+'\r\n'+data3;
// console.log(result);
// })
// })
// })
//使用 promise 对象
const p =new Promise((resolve,reject)=>{
fs.readFile('./01-let.html',(err,data)=>{
resolve(data);
})
})
p.then(value=>{
return new Promise((resolve,reject)=>{
fs.readFile('./02-let实践案例.html',(err,data)=>{
resolve([value,data]);
})
})
}).then(value=>{
return new Promise((resolve,reject)=>{
fs.readFile('./03-const.html',(err,data)=>{
value.push(data);
resolve(value)
})
})
}).then(value=>{
console.log(value.join('\r\n'));
})
Set
ES6 提供了新的数据结构 Set(集合)。它类似于数组,但成员的值都是唯一的,集合实现了 iterator 接口,所以可以使用『扩展运算符』和『for…of…』进行遍历,集合的属性和方法:
-
size 返回集合的元素个数
-
add 增加一个新元素,返回当前集合
-
delete 删除元素,返回 boolean 值
-
has 检测集合中是否包含某个元素,返回 boolean 值
-
clear 清空集合,返回 undefined
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>28-set</title>
</head>
<body>
<script>
//声明一个 set
let s = new Set();
let s2 = new Set(['a', 'b', 'c', 'a']);
console.log(s, typeof s); //Set(0)[[Entries]]No propertiessize: (...)__proto__: Set "object"
console.log(s2); //Set(3) {"a", "b", "c"}
//元素的个数
console.log(s2.size); //3
//添加新的元素
s2.add('d');
console.log(s2); //Set(4) {"a", "b", "c", "d"}
//删除元素
s2.delete('a');
console.log(s2); //Set(3) {"b", "c", "d"}
console.log(s2.has('a')); //false
console.log(s2.has('b')); //true
//清空
// s2.clear();
// console.log(s2); //Set(0) {}
for(let v of s2){
console.log(v); // b c d
}
</script>
</body>
</html>
set实践
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>29-set实践</title>
</head>
<body>
<script>
let arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
//1.数组去重
// let result=[...new Set(arr)];
// console.log(result); //[1,2,3,4,5]
//2.交集
let arr2 = [4, 5, 6, 5, 6];
// let result=[...new Set(arr)].filter(item=>{
// let s2=new Set(arr2);
// if (s2.has(item)) {
// return true;
// }
// else return false;
// });
let result=[...new Set(arr)].filter(item=>new Set(arr2).has(item));
console.log(result); //[4, 5]
//3.并集
let union = [...new Set([...arr,...arr2])];
console.log(union); //[1, 2, 3, 4, 5, 6]
//4.差集
let diff=[...new Set(arr)].filter(item=>!(new Set(arr2).has(item)));
console.log(diff); //[1, 2, 3]
</script>
</body>
</html>
Map
ES6 提供了 Map 数据结构。它类似于对象,也是键值对的集合。但是“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键。Map 也实现了iterator 接口,所以可以使用『扩展运算符』和『for…of…』进行遍历。Map 的属性和方法:
-
size 返回 Map 的元素个数
-
set 增加一个新元素,返回当前 Map
-
get 返回键名对象的键值
-
has 检测 Map 中是否包含某个元素,返回 boolean 值
-
clear 清空集合,返回 undefined
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>30-map</title>
</head>
<body>
<script>
//声明 Map
let m = new Map();
//添加元素
m.set('name', 'qinghua');
m.set('func', function () {
console.log('func');
})
m.set({ school: 'qinghua' }, ['北京', '中国']);
console.log(m); /* Map(3) {"name" => "qinghua", "func" => ƒ, {…} => Array(2)}
[[Entries]]
0: {"func" => function () { console.log('func'); }}
1: {Object => Array(2)}
size: (...)
__proto__: Map
*/
//size
console.log(m.size); //3
//删除
m.delete('name');
console.log(m); /*
Map(2) {"func" => ƒ, {…} => Array(2)}
[[Entries]]
0: {"func" => function () { console.log('func'); }}
key: "func"
value: ƒ ()
1: {Object => Array(2)}
key: {school: "qinghua"}
value: (2) ["北京", "中国"]
size: (...)
__proto__: Map
*/
//获取
console.log(m.get('func')); /* ƒ () {console.log('func');}*/
//清空
//m.clear();
for(let v of m){
console.log(v); /* 0: {school: "qinghua"}
1: (2) ["北京", "中国"]
length: 2
__proto__: Array(0)
*/
}
</script>
</body>
</html>
class类
ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过 class 关键字,可以定义类。基本上,ES6 的 class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象原型的写法更加清晰、更像面向对象程的语法而已。
知识点:
-
class 声明类
-
constructor 定义构造函数初始化
-
extends 继承父类
-
super 调用父级构造方法
-
static 定义静态方法和属性
-
父类方法可以重写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>31-类声明</title>
</head>
<body>
<script>
/*
//手机
function Phone(brand,price){
this.brand=brand;
this.price=price;
}
//添加方法
Phone.prototype.call=function(){
console.log('我可以打电话!!');
}
let Huawei=new Phone('华为',9999);
console.log(Huawei); /*Phone
brand: "华为"
price: 9999
__proto__:
call: ƒ ()
constructor: ƒ Phone(brand,price)
__proto__: Object
*/
//es6
class Phone {
constructor(brand, price) {
this.brand = brand;
this.price = price;
}
//方法必须使用该语法,不能使用 ES5 的对象完整形式
call() {
console.log("我可以打电话");
}
}
let OnePlus = new Phone();
OnePlus.call(); //我可以打电话
</script>
</body>
</html>
类的静态成员
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>静态成员</title>
</head>
<body>
<script>
/*
function Phone(){
}
Phone.name='手机';
Phone.change=function(){
console.log("我能改变自己");
}
Phone.prototype.size=5;
let nokia=new Phone();
console.log(nokia.name); //undefined
console.log(nokia.size); //5
*/
class Phone {
static name = '手机';
static change() {
console.log("我可以改变自己");
}
}
let nokia = new Phone();
console.log(nokia.name); //undefined
console.log(Phone.name); //手机
</script>
</body>
</html>
es5实现继承
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>33-类继承</title>
</head>
<body>
<script>
//手机
function Phone(brand, price) {
this.brand = brand;
this.price = price;
}
Phone.prototype.call = function () {
console.log("我可以打电话");
}
//子级 智能手机
function SmartPhone(brand, price, color, size) {
Phone.call(this, brand, price);
this.color = color;
this.size = size;
}
//设置子级构造函数的原型
SmartPhone.prototype=new Phone;
SmartPhone.prototype.constructor=SmartPhone;
//声明子类的方法
SmartPhone.prototype.photo=function(){
console.log("我可以拍照");
}
SmartPhone.prototype.playGame=function(){
console.log("我可以玩游戏");
}
const chuizi=new SmartPhone('锤子',3999,'黑色',6);
console.log(chuizi); /* {
"brand": "锤子",
"price": 3999,
"color": "黑色",
"size": 6
}*/
</script>
</body>
</html>
es6写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>34-类继承2</title>
</head>
<body>
<script>
class Phone{
//构造函数
constructor(brand,price){
this.brand=brand;
this.price=price;
}
call(){
console.log("我可以打电话");
}
}
class SmartPhone extends Phone{
//沟站函数
constructor(brand,price,color,size) {
super(brand,price);//Phone.call(this,brand,price)
this.color=color;
this.size=size;
}
photo(){
console.log("拍照");
}
playGame(){
console.log("玩游戏");
}
call(){
console.log("我可以视频通话");
}
}
const xiaomi=new SmartPhone('小米',799,'黑色','5.5');
xiaomi.call();//我可以视频通话 重写
xiaomi.photo()//拍照
console.log(xiaomi); /*{
"brand": "小米",
"price": 799,
"color": "黑色",
"size": "5.5"
}*/
</script>
</body>
</html>
get-set
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>get和set</title>
</head>
<body>
<script>
//get 和 set
class Phone{
get price(){
console.log("价格属性被读取了");
}
set price(newValue){
console.log('价格属性被修改了'); // 必须要有一个参数 Uncaught SyntaxError: Setter must have exactly one formal parameter.
}
}
let s=new Phone();
console.log(s.price); //价格属性被读取了 undefined
s.price=10; //价格属性被修改了
</script>
</body>
</html>
数值扩展
二进制和八进制
ES6 提供了二进制和八进制数值的新的写法,分别用前缀 0b 和 0o 表示。
Number.isFinite() 与 Number.isNaN()
Number.isFinite() 用来检查一个数值是否为有限的
Number.isNaN() 用来检查一个值是否为 NaN
Number.parseInt() 与 Number.parseFloat()
ES6 将全局方法 parseInt 和 parseFloat,移植到 Number 对象上面,使用不变。
Math.trunc
用于去除一个数的小数部分,返回整数部分。
Number.isInteger
Number.isInteger() 用来判断一个数值是否为整数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数值扩展</title>
</head>
<body>
<script>
//0.Number.EPSILON 是 Javascript 表示的最小精度
//EPSILON 属性的值接近于 2.220446049250313e-16
console.log(Number.EPSILON);
console.log(0.1+0.2); //0.30000000000000004
function equal(a,b){
if (Math.abs(a-b)<Number.EPSILON) {
return true;
}
else return false;
}
console.log(0.1+0.2===0.3); //false
console.log(equal(0.1+0.2,0.3));//true
//1.二进制和八进制
let b=0b1010; //二进制
console.log(b); //10
let o=0o777; //八进制
console.log(o); //511
let d=100; //十进制
console.log(d); //100
let x=0xff; //十六进制
console.log(x); //255
//2.Number.isFinite 检测一个数值是否为有限数
console.log(Number.isFinite(100)); //true
console.log(Number.isFinite(100/0)); //false
console.log(Number.isFinite(Infinity)); //false
//3.Number.isNaN 检测一个数值是否为 NaN
console.log(Number.isNaN(123));//false
//4.Number.parseInt Number.parseFloat字符串转整数、浮点数
console.log(Number.parseInt('5201314love')); //5201314
console.log(Number.parseFloat('3.1415926')); //3.1415926
//5.Number.isInteger 判断一个数是否为整数
console.log(Number.isInteger(5)); //true
console.log(Number.isInteger(2.3)); //false
//6.Math.trunc 将数字的小数部分抹掉
console.log(Math.trunc(3.5)); //3
//7.Math.sign 判断一个数到底为正数 负数 还是0
console.log(Math.sign(100)); //1
console.log(Math.sign(0)); //0
console.log(Math.sign(-200)); //-1
</script>
</body>
</html>
对象扩展
ES6 新增了一些 Object 对象的方法
-
Object.is 比较两个值是否严格相等,与『===』行为基本一致(+0 与 NaN)
-
Object.assign 对象的合并,将源对象的所有可枚举属性,复制到目标对象
-
proto、setPrototypeOf、 setPrototypeOf 可以直接设置对象的原型
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>37-对象方法扩展</title>
</head>
<body>
<script>
//1.Object.is 判断两个值是否完全相等
console.log(Object.is(120, 121)); //false
console.log(Object.is(NaN, NaN)); //true
console.log(NaN === NaN); //false
//2.Object.assign 对象的合并
const config1 = {
host: 'localhost',
port: 3306
}
const config2 = {
host:'http://mcode.cn',
port: 3306,
user:'root'
}
let result = Object.assign(config1, config2);
console.log(result); /* {
"host": "http://mcode.cn",
"port": 3306,
"user": "root"
}*/
//3.Object.setPrototypeOf 设置原型对象 Object.getPrototypeof
const school={
name:'清华'
};
const cities={
xiaoqu:['中国','北京']
};
Object.setPrototypeOf(school,cities);
console.log(school); /* {name: "清华"}
name: "清华"
__proto__:
xiaoqu: (2) ["中国", "北京"]
__proto__: Object*/
console.log(Object.getPrototypeOf(school)); /*{
"xiaoqu": [
"中国",
"北京"
]
}*/
</script>
</body>
</html>
模块化
模块化是指将一个大的程序文件,拆分成许多小的文件,然后将小文件组合起来。
模块化的优势有以下几点:
-
防止命名冲突
-
代码复用
-
高维护性
ES6 之前的模块化规范有:
-
CommonJS => NodeJS、Browserify
-
AMD => requireJS
-
CMD => seaJS
模块功能主要由两个命令构成:export 和 import。
export 命令用于规定模块的对外接口
import 命令用于输入其他模块提供的功能
分别暴露:
//分别暴露
export let code = 'java';
export function getCode() {
console.log('code');
}
统一暴露:
//统一暴露
let school = '清华';
function findJob() {
console.log('找任务');
}
export { school, findJob }
默认暴露:
//默认暴露
export default {
school:'vmcode',
change:function(){
console.log('改变');
}
}
import的几种方式
1.通用的导入方式
2.解构赋值形式
3.简便形式 只能针对默认暴露
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>38-ES6模块化</title>
</head>
<body>
<script type="module">
//1.通用的导入方式
//引入 38-分别暴露.js 模块内容
import * as m38 from './38-分别暴露.js';
console.log(m38); /*Module {Symbol(Symbol.toStringTag): "Module"}
code: (...)
getCode: (...)
Symbol(Symbol.toStringTag): "Module"
get code: ƒ ()
set code: ƒ ()
get getCode: ƒ ()
set getCode: ƒ ()
*/
//引入 38-统一暴露.js
import * as m39 from './38-统一暴露.js';
console.log(m39); /*Module {Symbol(Symbol.toStringTag): "Module"}
findJob: (...)
school: (...)
Symbol(Symbol.toStringTag): "Module"
get findJob: ƒ ()
set findJob: ƒ ()
get school: ƒ ()
set school: ƒ ()
*/
//引入 38-默认暴露.js
import * as m40 from './38-默认暴露.js';
console.log(m40); /*Module {Symbol(Symbol.toStringTag): "Module"}
default: Object
change: ƒ ()
school: "vmcode"
__proto__: Object
Symbol(Symbol.toStringTag): "Module"
get default: ƒ ()
set default: ƒ ()
*/
m40.default.change(); //改变
//2.解构赋值形式
import {code,getCode} from './38-分别暴露.js';
import {school as qinghua,findJob} from './38-统一暴露.js';
import {default as default1} from './38-默认暴露.js'
console.log(code); //java
console.log(getCode); /*ƒ getCode() {
console.log('code');
}*/
console.log(qinghua); //清华
console.log(findJob); /*ƒ findJob() {
console.log('找任务');
}*/
console.log(default1); /* school: "vmcode", change: ƒ}*/
//3.简便形式 只能针对默认暴露
import default2 from './38-默认暴露.js';
console.log(default2); /* school: "vmcode", change: ƒ}*/
</script>
<script src="./38-app.js" type="module"></script>
</body>
</html>
babel打包
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./dist/bundle.js">
//1.安装工具 babel-cli babel-preset-env browserify(webpack)
//2.npx babel ./js -d dist/js --presets=babel-preset-env
//4.打包 npx browserify dist/js/38-app.js -o dist/bundle.js
</script>
</body>
</html>
npm init --yes
npm i babel-cli babel-preset-env browserify -D
npx babel ./js -d dist/js --presets=babel-preset-env
npx browserify dist/js/38-app.js -o dist/bundle.js
ECMAScript系列:ES7新特性
Array.prototype.includes
Includes 方法用来检测数组中是否包含某个元素,返回布尔类型值
//includes indexOf
const arr=['a','b','c'];
console.log(arr.includes('d')); // false
console.log(arr.includes('a')); //true
指数操作符
在 ES7 中引入指数运算符「**」,用来实现幂运算,功能与 Math.pow 结果相同
//**
console.log(2 ** 10); //1024
console.log(Math.pow(2,10)); //1024
ECMAScript系列:ES8新特性
async 和 await
async 和 await 两种语法结合可以让异步代码像同步代码一样
async 函数
async 函数的返回值为 promise 对象,
promise 对象的结果由 async 函数执行的返回值决定
//async 函数
async function fn() {
//返回一个字符串
//return 'code';
//返回的结果不是一个 promise 类型的对象;返回的结果就是成功 promise对象
//return;
//抛出错误,返回的结果是一个失败的 promise
//throw new Error('error');
return new Promise((resolve, reject) => {
//resolve('success data.');
//reject('fail data.')
})
}
const result = fn();
console.log(result)
result.then(value => {
console.log(value);
}, reason => {
console.warn(reason)
});
await 表达式
await 必须写在 async 函数中
await 右侧的表达式一般为 promise 对象
await 返回的是 promise 成功的值
await 的 promise 失败了, 就会抛出异常, 需要通过 try…catch 捕获处理
//创建 promise 对象
const p = new Promise((resolve, reject) => {
//resolve('success data.')
reject('fail data.');
})
//await 要放在 async 函数中.
async function main() {
try {
let result = await p;
console.log(result)
} catch (e) {
console.log(e)
}
}
//调用函数
main();
案例
//1.引入 fs 模块
const fs = require('fs');
function read1() {
return new Promise((resolve, reject) => {
fs.readFile('./1-async.html', (err, data) => {
//如果失败
if (err) {
reject(err);
} else resolve(data);
});
})
}
function read2() {
return new Promise((resolve, reject) => {
fs.readFile('./2-await.html', (err, data) => {
//如果失败
if (err) {
reject(err);
} else resolve(data);
});
})
}
//声明一个async 函数
async function main() {
let readFile1 = await read1();
let readFile2 = await read2();
console.log(readFile1.toString());
console.log(readFile2.toString())
}
main();
async和await封装ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>封装ajax请求</title>
</head>
<body>
<script>
//发送ajax请求,返回的结果是 Promise 对象
function sendAjax(url) {
return new Promise((resolve, reject) => {
//1.创建对象
const x = new XMLHttpRequest();
//2.初始化
x.open('GET', url);
//3.发送
x.send();
//4.事件绑定
x.onreadystatechange = () => {
if (x.readyState === 4) {
if (x.status >= 200 && x.status < 300) {
resolve(x.response);
}
else {
reject(x.status);
}
}
}
});
}
// promise 测试
sendAjax("https://api.apiopen.top/getJoke").then(value => {
console.log(value);
}, reason => {
console.log(reason);
})
// async 和 await 测试
async function mian(){
let result= await sendAjax("https://api.apiopen.top/getJoke");
console.log(result)
}
mian();
</script>
</body>
</html>
Object.values 和 Object.entries
Object.values()方法返回一个给定对象的所有可枚举属性值的数组
Object.entries()方法返回一个给定对象自身可遍历属性 [key,value] 的数组
//声明对象
const school={
name:'清华',
city:['北京'],
subject:['web','dotnet','java']
}
//获取对象所有的键
console.log(Object.keys(school));// ["name", "city", "subject"]
//获取对象所有的值
console.log(Object.values(school)); //["清华", Array(1), Array(3)]
//获取对象的键值对
console.log(Object.entries(school)); // [Array(2), Array(2), Array(2)]
const m=new Map(Object.entries(school));
console.log(m);//Map(3) {"name" => "清华", "city" => Array(1), "subject" => Array(3)}
Object.getOwnPropertyDescriptors
该方法返回指定对象所有自身属性的描述对象
//对象属性的描述对象
console.log(Object.getOwnPropertyDescriptors(school));
/*
city: {value: Array(1), writable: true, enumerable: true, configurable: true}
name: {value: "清华", writable: true, enumerable: true, configurable: true}
subject: {value: Array(3), writable: true, enumerable: true, configurable: true}
__proto__: Object
*/
const obj=Object.create(null,{
name:{
//设置值
value:'清华',
//属性特性
writable:true,
configurable:true,
enumerable:true,
}
})
ECMAScript系列:ES9新特性
Rest/Spread 属性
Rest 参数与 spread 扩展运算符在 ES6 中已经引入,不过 ES6 中只针对于数组,
在 ES9 中为对象提供了像数组一样的 rest 参数和扩展运算符
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>对象展开</title>
</head>
<body>
<script>
/* Rest 参数 与 spread 扩展运算符在 ES6 中已经引入,不过 ES6 中只针对数组,
在 ES9 中为对象提供了像数组一样的 Rest 参数和扩展运算符*/
function connect({ host, port, ...user }) {
console.log(host);
console.log(port);
console.log(user)
}
connect({ host: '127.0.0.1', port: 3306, username: 'root', password: 'root' });
const skillOne = {
q: 'qq'
};
const skillTwo = {
w: 'ww'
};
const skillThree = {
e: 'ee'
}
const mengseng = { ...skillOne, ...skillTwo, ...skillThree };
console.log(mengseng); //{q: "qq", w: "ww", e: "ee"}
</script>
</body>
</html>
正则表达式命名捕获组
ES9 允许命名捕获组使用符号『?』,这样获取捕获结果可读性更强
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>正则表达式命名捕获组</title>
</head>
<body>
<script>
//声明一个字符串
let str = '<a href="http://vmcode.com">vmcode</a>';
//提取 url 与 标签文本
const reg = /<a href="(.*)">(.*)<\/a>/;
//执行
const result = reg.exec(str); /* 0: "<a href="http://vmcode.com">vmcode</a>"
1: "http://vmcode.com"
2: "vmcode"
groups: undefined
index: 0
input: "<a href="http://vmcode.com">vmcode</a>"
length: 3
*/
console.log(result);
console.log(result[1]);
console.log(result[2]);
</script>
<script>
//声明一个字符串
let str1 = '<a href="http://vmcode.com">vmcode</a>';
//提取 url 与 标签文本
const reg1 = /<a href="(?<url>.*)">(?<text>.*)<\/a>/;
const result1=reg1.exec(str1);
console.log(result1) /* ["<a href="http://vmcode.com">vmcode</a>", "http://vmcode.com", "vmcode", index: 0, input: "<a href="http://vmcode.com">vmcode</a>", groups: {…}]
0: "<a href="http://vmcode.com">vmcode</a>"
1: "http://vmcode.com"
2: "vmcode"
groups: {url: "http://vmcode.com", text: "vmcode"}
index: 0
input: "<a href="http://vmcode.com">vmcode</a>"
length: 3
*/
console.log(result1.groups.url); //http://vmcode.com
</script>
</body>
</html>
正则表达式反向断言
ES9 支持反向断言,通过对匹配结果前面的内容进行判断,对匹配进行筛选。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>正则表达式反向断言</title>
</head>
<body>
<script>
//声明一个字符串
let str = 'JS123456你知道吗555啦啦啦';
//正向断言
const reg=/\d+(?=啦)/;
const result=reg.exec(str);
console.log(result); /*0: "555"
groups: undefined
index: 12
input: "JS123456你知道吗555啦啦啦"
length: 1
__proto__: Array(0)
*/
//反向断言
const reg1=/(?<=吗)\d+/;
const result1=reg1.exec(str);
console.log(result1); /*0: "555"
groups: undefined
index: 12
input: "JS123456你知道吗555啦啦啦"
length: 1
__proto__: Array(0)
*/
</script>
</body>
</html>
正则表达式 dotAll 模式
正则表达式中点.匹配除回车外的任何单字符,标记『s』改变这种行为,允许行终止符出现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>正则表达式-dotAll模式</title>
</head>
<body>
<script>
//dot . 元字符 除换号符以外的任意单个字符
let str = `<ul>
<li>
<a>肖生克的救赎</a>
<p>上映日期:1994-09-10</p>
</li>
<li>
<a>阿甘正传</a>
<p>上映日期:1994-07-06</p>
</li>
</ul>`;
const reg = /<li>\s+<a>(.*?)<\/a>\s+<p>(.*?)<\/p>/;
const result = reg.exec(str);
console.log(result); /* 0: "<li>↵ <a>肖生克的救赎</a>"
1: "肖生克的救赎"
groups: undefined
index: 25
input: "<ul>↵ <li>↵ <a>肖生克的救赎</a>↵ <p>上映日期:1994-09-10</p>↵ </li>↵ <li>↵ <a>阿甘正传</a>↵ <p>上映日期:1994-07-06</p>↵ </li>↵ </ul>"
length: 2
__proto__: Array(0)
*/
const reg1 = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/s;
const result1 = reg1.exec(str);
console.log(result1); /*0: "<li>↵ <a>肖生克的救赎</a>↵ <p>上映日期:1994-09-10</p>"
1: "肖生克的救赎"
2: "上映日期:1994-09-10"
groups: undefined
index: 25
input: "<ul>↵ <li>↵ <a>肖生克的救赎</a>↵ <p>上映日期:1994-09-10</p>↵ </li>↵ <li>↵ <a>阿甘正传</a>↵ <p>上映日期:1994-07-06</p>↵ </li>↵ </ul>"
length: 3
__proto__: Array(0
*/
const reg2 = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/gs;
let result2;
let data = [];
while (result2 = reg2.exec(str)) {
//console.log(result2[1]);
data.push({ title: result2[1], time: result2[2] });
}
console.log(data); /*0: {title: "肖生克的救赎", time: "上映日期:1994-09-10"}
1: {title: "阿甘正传", time: "上映日期:1994-07-06"}
length: 2
*/
</script>
</body>
</html>
ECMAScript系列:ES10新特性
Object.fromEntries
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object.fromEntries</title>
</head>
<body>
<script>
//二维数组
const result = Object.fromEntries([
['name', 'vmcode'],
['tags', 'web,java']
])
console.log(result); //{name: "vmcode", tags: "web,java"}
//Map
const m = new Map();
m.set('name','vmcode');
const result1 = Object.fromEntries(m);
console.log(result1); //{name: "vmcode"}
const arr=Object.entries({ name:'vmcode'});
console.log(arr); /*[
[
"name",
"vmcode"
]
]*/
</script>
</body>
</html>
trimStart 和 trimEnd
//trim
let str=' i can ';
console.log(str);
console.log(str.trimStart(str));
console.log(str.trimEnd(str));
Array.prototype.flat 与 flatMap
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>flat 与 flatMap</title>
</head>
<body>
<script>
//flat 平
//将多维数组转化为低位数组
const arr = [1, 2, 3, [4, 5]];
console.log(arr.flat()); //[1,2,3,4,5]
const arr1 = [1, 2, [3, 4, [5, 6]]];
console.log(arr1.flat()); //[1,2,3,4,[5,6]]
//参数为深度 是一个数子
console.log(arr.flat(2));//[1,2,3,4,5,6]
//flatMap
const arr2 = [1, 2, 3, 4];
const result1 = arr2.map(item => item * 10);
console.log(result1); // [10, 20, 30, 40]
const result2 = arr2.flatMap(item => [item * 10]);
console.log(result2); // [10, 20, 30, 40]
</script>
</body>
</html>
Symbol.prototype.description
//创建 Symbol
let s =Symbol('vmcode');
console.log(s.description); //vmcode
ECMAScript系列:ES11新特性
String.prototype.matchAll
<script>
//用来得到正则批量结果
let str = `<ul>
<li>
<a>肖生克的救赎</a>
<p>上映日期:1994-09-10</p>
</li>
<li>
<a>阿甘正传</a>
<p>上映日期:1994-07-06</p>
</li>
</ul>`;
//声明正则
const reg=/<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/sg
//得到结果
const result=str.matchAll(reg);
console.log(result); //RegExpStringIterator {}
// for(let v of result){
// console.log(v[1]);
// }
const arr=[...result];
console.log(arr); /* (2) [Array(3), Array(3)]
0: (3) ["<li>↵ <a>肖生克的救赎</a>↵ <p>上映日期:1994-09-10</p>", "肖生克的救赎", "上映日期:1994-09-10", index: 25, input: "<ul>↵ <li>↵ …>↵ </li>↵ </ul>", groups: undefined]
1: (3) ["<li>↵ <a>阿甘正传</a>↵ <p>上映日期:1994-07-06</p>", "阿甘正传", "上映日期:1994-07-06", index: 159, input: "<ul>↵ <li>↵ …>↵ </li>↵ </ul>", groups: undefined]
length: 2
__proto__: Array(0)*/
类的私有属性
<script>
class Person {
//公有属性
name;
//私有属性
#age;
#weight;
constructor(name, age, weight) {
this.name = name;
this.#age = age;
this.#weight = weight;
}
intro(){
console.log(this.#age);
console.log(this.name);
}
}
//实例化
const girl = new Person('vmcode', 18, 250);
console.log(girl); /*{name: "vmcode"#age: 18 #weight: 25}*/
console.log(girl.name); //vmcode
//console.log(girl.#age); // Private field '#age' must be declared in an enclosing class
girl.intro();
Promise.allSettled
//适用于批量Promise
//声明两个promise对象
const p1=new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve('product data -1')
},1000)
})
const p2=new Promise((resolve,reject)=>{
setTimeout(()=>{
reject('product data -2')
},1000)
})
//调用 allsettled 方法 始终是个成功
const result=Promise.allSettled([p1,p2]);
console.log(result); /* __proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(2)
0: {status: "fulfilled", value: "product data -1"}
1: {status: "fulfilled", value: "product data -2"}
length: 2
__proto__: Array(0)
*/
//要么都成功,要么就显示失败
const res=Promise.all([p1,p2]);
console.log(res); /*__proto__: Promise
[[PromiseResult]]: "product data -2"
[[PromiseState]]: "rejected"
*/
可选链操作符
//?.
function mian(config){
//const dbHost=config.db.host;
const dbHost=config?.db?.host;
console.log(dbHost);
}
//mian({db:{host:'127.0.0.1',username:'root'},cache:{host:'127.0.0.1',username:'admin'}})
mian();
动态 import 导入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态import</title>
</head>
<body>
<button id='btn'>btn</button>
<script src="./js/app.js" type="module"></script>
</body>
</html>
App.js
//import * as m1=from './hello.js'
const btn=document.getElementById('btn');
btn.onclick=function(){
import('./hello.js').then(moudle=>{
console.log(moudle);
moudle.hello();
})
}
Hello.js
export function hello(){
console.log('hello');
}
BitInt
let n=512n;
console.log(n,typeof(n)) //512n "bigint"
//函数
let n1=123;
console.log(BigInt(n1)); //123n
//console.log(BitInt(1.2)); // BitInt is not defined
//大数值运算
let max=Number.MAX_SAFE_INTEGER;
console.log(max);//9007199254740991
console.log(max+1); //9007199254740992
console.log(max+2); //9007199254740992
console.log(BigInt(max));//9007199254740991n
console.log(BigInt(max)+BigInt(1)); //9007199254740992n
console.log(BigInt(max)+BigInt(2)); //9007199254740993n
globalThis 对象
html下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>globalThis</title>
</head>
<body>
<script>
console.log(globalThis); //window
</script>
</body>
</html>
nodejs下
console.log(globalThis); //global