乐趣区

关于javascript:ES6ES11新特性

ES6-ES11

Author:gavin,本文是尚硅谷 ES 学习集体笔记
视频链接

ES6

P2- 什么是 ES6?

P3-let 变量成名及个性

  1. 不能反复申明
  2. 块级作用域
  3. 不存在变量晋升,在申明前写无用
  4. 不影响作用链

P4-let 练习

P5-const 申明常量及特点

  1. 肯定要赋初始值
  2. 个别常量应用大写
  3. 常量值不能批改(个别用数组,对象)
  4. 块级作用域

P6- 解构赋值

// 1. 数组解构
const F4 = ["小明", "小红", "小亮", "小白"];
let [mk, hs, ll, bd] = F4;

// 2. 对象解构
const ming = {
  name: "小明",
  age: "18",
};
let {name, age} = ming;

P7- 模板字符串

// 1. 申明
let str = `I am string`;

// 2. 内容可间接呈现换行符
let str = `<span>isString</span>`;

// 3. 变量拼接
let lovest = "刘德华";
let out = `${lovest}是我的偶像 `;

P8- 对象简写办法

let name = '小明',
let age = 18,
const person={
  name,
  age,
  improve(){console.log('我能工作')
  }
}

P9- 箭头函数及申明

// 申明
let fn = function () {};
let fn = (a, b) => {return a + b;};

// 调用
fn(a, b);

// 1. this 始终指向所在作用域下的 this 的值

// 2. 不能作为结构实例对象办法
let Person = (name, age) => {
  this.name = name;
  this.age = age;
};
let me = new Person("xiaoming", 20);

// 3. 不能应用 arguments 变量
let fn = () => {console.log(arguments);
};
fn(1, 2, 3);

// 4. 箭头函数简写
// 形参惟一,可省略小括号
// 代码体一句,省略花括号, 此时 return 必须省略, 且语句执行后果即返回值
let pow = (n) => n * n;

P10- 箭头函数利用场景

// 1. 定时器回调,应用作用域 this
// 2. 从数组中返回偶数元素
const arr = [1, 5, 6, 7, 652];
const result = arr.filter((item) => item % 2 === 0);
console.log(result);

// 适宜与 this 无关回调,定时器、数组办法回调
// 不适宜与 this 无关的回调, 事件回调、对象的办法

P11- 函数参数默认值设置

// 1. 形参初始值,有默认值的参数,地位要靠后(潜规则)add(a,b,c=10){return a + b + c;}
let result add(1,2);

// 2. 与解构赋值联合
function connect({host = "127.0.0.1", username, password, port}) {console.log(host);
      console.log(username);
      console.log(password);
      console.log(port);
    }
    connect({
      username: "root",
      password: "root",
      port: 3306,
    });

P12- rest 参数

// ES5 获取实参
function date() {console.log(arguments);
}
date("ming", "gavin", "lily");

// rest 参数必许放到参数最初
function date(a, b, ...args) {console.log(args); // 数组
}
date(1, 2, 3, 4, 5, 6);

P13-P14 扩大运算符介绍及使用

“…” 扩大运算符能将 ” 数组 ” 转化为 ” 参数序列 ”

// 1. 数组合并
const arr = [1, 2, 3, 4, 5];
const fh = ["增益", "零花"];
const he = [...arr, ...fh];
console.log(he);
// 2. 数组的克隆
const szh = ["E", "G"];
const syc = [...szh];
console.log(syc);
//3. 将伪数组转为真正数组
const divs = document.querySelectorAll("div");
const divArr = [...divs];
console.log(divArr);

P15-Symbol 的介绍与创立

js 的第七种类型,用来解决命名抵触

// 创立 Symbol
let s = Symbol();
let s2 = Symbol("gavin");
let s3 = Symbol("gavin");
console.log(s2 === s3);
let s4 = Symbol.for("gavin");
console.log(s4, typeof s4);
// 不能与其余数据进行计算
// let result = s + s;
// USONB
// u undefined
// s String Symbol
// o Object
// n null Number
// b Boolean

P16-Symbol 的使用

const game = {up() {console.log("up!");
  },
  down() {console.log("down");
  },
};
// First: 向一对象内部增加 Symbol;
let methods = {up: Symbol(),
  down: Symbol(),};
game[methods.up] = () => {console.log("Up To");
};
game[methods.down] = () => {console.log("Down to");
};
console.log("game 对象", game);
// Second: 外部定义 Symbol
let steam = {
  name: "狼人杀",
  [Symbol("say")]: () => {console.log("I can Say!");
  },
  [Symbol("run")]: () => {console.log("Run to world");
  },
};
console.log("steam", steam);

P17-Symbol 的内置属性(不罕用)

P18-19 迭代器介绍???

// 迭代器遍历对象原理
const four = ["唐僧", "孙悟空", "沙僧"];
let iterator = four[Symbol.iterator]();
// console.log(iterator.next());
// 申明对象
const myclass = {
  name: "高一一班",
  studensts: ["ming", "ling", "星星"],
  [Symbol.iterator]() {
    // 索引变量
    let index = 0;
    let _this = this;
    return {next: function () {if (index < _this.studensts.length) {const result = { value: _this.studensts[index], done: false };
          // 下标自增,返回后果
          index++;
          return result;
        } else {return { value: undefined, done: true};
        }
      },
    };
  },
};
// 遍历对象且为 students 成员
for (let v of myclass) {console.log(v);
}

P20- 生成器函数申明和调用

// 生成器是一个非凡的函数
// 异步编程、纯回调函数、node fs  ajax  mongodb
function* gen() {
  yield "一只羊";
  yield "两只羊";
  yield "三只羊";
}

// let iterator = fen();
for (let v of gen()) {console.log(v);
}

P21- 生成器函数的参数传递

function* gen(arg) {console.log(arg);
  let one = yield 111;
  console.log(one);

  let two = yield 222;
  console.log(two);

  let three = yield 333;
  console.log(three);
}

// 执行获取迭代器对象
let iterator = gen("AAA");
console.log(iterator.next());
// next 办法可传实参
console.log(iterator.next("BBB"));
console.log(iterator.next("CCC"));
console.log(iterator.next("DDD"));

P22-P23 生成器函数实例

// 异步编程 文件操作 网络操作 数据库操作
// 需要: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();}

// 第二个例子
function getUsers() {setTimeout(() => {
    let data = "用户数据";
    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 user = yield getUsers();
  console.log(user);
  let orders = yield getOrders();
  console.log(orders);
  let goods = yield getGoods();
  console.log(goods);
}
// 调用生成器函数
let iterator = gen();
iterator.next();

P24-Promise 介绍与根本应用

const p = new Promise(function (resolve, reject) {setTimeout(() => {
    // let data = "数据库中的数据";
    // resolve(data);
    let err = "数据读取失败";
    reject(err);
  }, 1000);
});
p.then(function (value) {console.log(value);
  },
  function (reason) {console.log(reason);
  }
);

P25-Promise 封装读取文件

const fs = require("fs");
const p = new Promise(function (resolve, reject) {fs.readFile("./es6 学习.md", (err, data) => {
    // 判断失败
    if (err) reject(err);
    // 胜利
    resolve(data);
  });
});
p.then((value) => {console.log(value.toString());
  },
  (err) => {console.log("失败!!!", err);
  }
);

P26-Promise 封装 AJAX 申请

const p = new Promise((resolve, reject) => {
  // 创建对象
  const xhr = new XMLHttpRequest();
  // 初始化
  xhr.open(
    "GET",
    "http://rap2api.taobao.org/app/mock/293221/manage/category/info"
  );
  // 发送
  xhr.send();
  // 绑定事件
  xhr.onreadystatechange = function () {if (xhr.readyState === 4) {if (xhr.status >= 200 && xhr.status < 300) {resolve(xhr.response);
      } else {reject(xhr.status);
      }
    }
  };
});
// 指定回调
p.then(function (value) {console.log(value);
  },
  (reason) => {console.log(reason);
  }
);

P27-Promise.prototype.then 办法

// 创立 Promise 对象
const p = new Promise(function (resolve, reject) {setTimeout(() => {
    let data = "数据库中的数据";
    resolve(data);
    // let err = "数据读取失败";
    // reject(err);
  }, 1000);
});
// 调用 then 办法,then 办法的返回后果是 Promise 对象,对象状态由回调函数的执行后果决定
// 1. 返回后果是 非 promise 类型的属性,状态为胜利, 返回值为对象胜利值。// 链式调用
p.then(function (value) {console.log(value);
}).then((result) => {console.log(result);
});

28-Promise 实际练习 - 多个文件内容读取

import fs = require('fs')
fs.readFile("./resources/one.md", (err, data) => {});
const p =new Promise((resolve,reject) => {fs.readFile('./one.md'),(err,data) => {resolve(data);
  }
})
p .then((value) => {return new Promise((resolve,reject) => {fs.readFile('./two.md',(err,data) => {resolve([value,data])
  })
  })
}).then((value) => {return new Promise((resolve,reject) => {fs.readFile('./three.md',(err,data) => {value.push(data);
    resolve(value)
  })
  })
}).then((value) => {console.log(value)
})

P29-Promise 的 catch 办法

const p = new Promise((resolve, reject) => {setTimeout(() => {reject("err");
  }, 1000);
});
p.then((result) => {console.log(result);
}).catch((err) => {console.log(err);
});

P30- 汇合介绍与 API

// 申明一个 set
let s = new Set();
let s2 = new Set(["123", "456", "789", "123"]);
// 元素个数
console.log(s2.size);
// 增加新的元素
s2.add("000");
// 删除元素
s2.delete("111");
// 检测
console.log(s2.has("789"));
// 清空
s2.clear(s2);
console.log(s2);
// forof 遍历
for (let v of s2) {console.log(v);
}

P31- 汇合实际

let arr = [1, 2, 3, 4, 5, 6, 7, 1, 2, 3];
// 数组去重
let result = [...new Set(arr)];
console.log(result);
// 交加
let arr2 = [4, 5, 6, 7];
// result = result.filter((item) => {//   let s2 = new Set(arr2);
//   if (s2.has(item)) {
//     return true;
//   } else {
//     return false;
//   }
// });
result = [...new Set(arr)].filter((item) => new Set(arr2).has(item));
console.log(result);
// 并集
let union = [...new Set([...arr, ...arr2])];
console.log(union);
// 差集
let diff = [...new Set(arr)].filter((item) => !new Set(arr2).has(item));
console.log(diff);

P32-Map 的介绍与 API

// 申明 Map
let m = new Map();
// 增加元素
m.set("name", "gavin");
m.set("change", () => {console.log("We can change!");
});
let key = {school: "SCHOOL",};
m.set(key, ["北京", "上海", "广州"]);
// size
console.log(m.size);
// 删除
m.delete("name");
// 获取
console.log(m.get("change"));
console.log(m.get(key));
// 清空
m.clear();
// 遍历
for (const v of m) {console.log(v);
}

P33-class 意识

// ES5 函数工厂
function Phone(brand, price) {
  this.brand = brand;
  this.price = price;
}
Phone.prototype.call = function () {console.log("我可打电话!");
};
// 实例化对象
let Huawei = new Phone("华为", 666);
Huawei.call();
console.log(Huawei);
// ES6 类
class shouji {
  // 构造方法
  constructor(brand, price) {
    this.brand = brand;
    this.price = price;
  }
  call() {"我可 Call you!";}
}
let oppo = new shouji("oppo", 9999);
console.log(oppo);

P34-class 动态成员

// ES5
function Phone() {}
(Phone.name = "手机"),
  (Phone.change = function () {console.log("我可扭转世界");
  });
Phone.prototype.size = "5 英尺";
let nokia = new Phone();
console.log(nokia.name);
console.log(nokia.size);
// ES6
class Phone {
  // 动态成员
  static name = "手记";
  static change() {console.log("you cab change world!");
  }
}
let nokia = new Phone();
console.log(nokia.name);
console.log(Phone.name);

P35-ES5 构造函数继承

// 手机
function Phone(brand, price) {
  this.brand = brand;
  this.price = price;
}
Phone.prototype.call = function () {console.log("我可 Call you!");
};
// 智能手机
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.playGame = function () {console.log("我可打游戏");
};
const oppo = new SmartPhone("OPPO", 1234, "White", "6inch");
console.log(oppo);

P36-class 的类继承 P37- 子类对父类办法的重写

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);
    this.color = color;
    this.size = size;
  }
  photo() {console.log("我可拍照!");
  }
  playGame() {console.log("我可打游戏");
  }
  call() {console.log("我可视频通话!!!");
  }
}
const xiaomi = new SmartPhone("小米", 1221, "粉色", "6 英寸");
console.log(xiaomi);
xiaomi.call();
xiaomi.photo();
xiaomi.playGame();

P38-getter 和 setter 的设置

class Phone {get price() {console.log("价格属性被读取");
    return "isme";
  }
  get price() {console.log("价格属性被批改");
  }
}
let s = new Phone();
console.log(s);
s.price = "free";

P39-40-ES6 的数值扩大 && 对象办法扩大

// Object.assign 对象合并
const config1 = {
  host: "localhost3000",
  prot: 3306,
  name: "root",
  test: "2",
};
const config2 = {
  host: "localhost5000",
  prot: 3307,
  name: "gavin",
};
console.log(Object.assign(config1, config2));
// {host: 'localhost5000', prot: 3307, nam: 'gavin'}

P41-P42-P43-P44- 模块化

ES6 之前的模块化标准有:

  1. CommonJS => NodeJS、Browserify
  2. AMD => requireJS
  3. CMD => seaJS

模块性能次要由两个命令形成:export 和 import。

  • export 命令用于规定模块的对外接口
  • import 命令用于输出其余模块提供的性能
// 1. 通用导入形式
import * as m1 from "./a.js";
// 2. 解构赋值模式
import {school, teacher} from "./a.js";
import {school as guigu, teacher} from "./a.js";
// 3. 简便模式(针对默认裸露)
import A from "./a.js";

P45- 浏览器应用 ES6 的另一种形式

P46-babel 对 ES6 模块化代码转换

  1. 装置工具 babel-cli babel-preset-env browerify(webpack)
  2. 转译 npx babel src/js -d dist/js
  3. 打包 npx browserify dist/js/app.js -o dist/bundle.js

P47-ES6 模块化引入 NPM 包

P48-ES7 新个性

  • includes 判断数组是否含有某元素
  • 2 ** 10 (2 的 10 次方)

P49-ES8 async 函数

async function fn() {
  // 1. 返回一个字符串
  // return "硅谷";
  // 只有不回调 reject, 就是胜利 Promise 对象
  // return;
  // 2. 抛出谬误,返回后果为一个失败的 Promise 对象
  // return new Error("出错了");
  // 3. 返回的后果为 Promise 对象
  return new Promise((resolve, reject) => {// resolve("胜利");
    reject("失败");
  });
}
const result = fn();
console.log(result);
// 调用 then 办法
result.then((value) => {console.log(value);
  },
  (err) => {console.warn(err);
  }
);

P50-P51-ES8-async 与 await 读取文件内容

function study() {fs.readFile("../es6 学习.md", (err, data) => {if (err) reject(err);
    resolve(data);
  });
}
async function main() {let study = await study();
  console.log(study.toString());
}
main();

P52-async 与 await 联合发申请

用同步的办法写异步申请,await 期待后能收到具体值,非 Promise 对象

// 申请封装
function sendAJAX() {return new Promise((resolve, reject) => {
    //  1. 创建对象
    const x = new XMLHttpRequest();
    // 2. 初始化
    x.open("GET", url);
    // 3. 发送
    x.send();
    // 4. 事件绑定
    x.onreadystatechange = function () {if (x.readyState === 4) {if (x.status >= 200 && x.status < 300) {resolve(x.response);
        } else {reject(x.status);
        }
      }
    };
  });
}
// promise then 办法测试
// sendAJAX("http://rap2api.taobao.org/app/mock/293221/manage/user/add")
//   .then((value) => {//     console.log(value);
//   })
//   .catch((err) => {//     console.log(err);
//   });
// async 与 await 测试
async function main() {
  let result = await sendAJAX("http://rap2api.taobao.org/app/mock/293221/manage/user/add");
  console.log(result);
}

P53-ES8 对象办法扩大

const school = {
  name: "硅谷",
  subject: ["web", "JAVA", "大数据"],
};
//  获取对象所有键
console.log(Object.keys(school));
// 获取对象所有值
console.log(Object.values(school));
// 获取 entries 对象
console.log(Object.entries(school));
// ★ 多用来创立 Map
const m = new Map(Object.entries(school));
console.log(m);
// 创立属性的形容对象
console.log(Object.getOwnPropertyDescriptors(school));

P54-ES9 扩大运算符与 rest 参数

// ES9 中为对象提供了和数组一样的 rest 参数和扩大运算符
function connect({host, port, ...user}) {console.log(host), console.log(port), console.log(user);
}
connect({
  host: "localhost",
  port: "3306",
  username: "gavin",
  password: "12345",
});
const skillOne = {q: "吃饭",};
const skillTwo = {
  w: "睡觉",
  e: "打游戏",
};
const gavin = {...skillOne, ...skillTwo};
console.log(gavin);

P55-ES9 正则扩大 - 命名捕捉分组

将合乎正则的数据收集并命名

// 申明字符串
let str = "<a href='www.bilibili.com'>b 站 </a>";
// 提取 url 和[标签文本]
// const reg = /<a href='(.*)'>(.*)<\/a>/;
// 命名捕捉分组
const reg = /<a href='(?<url>.*)'>(?<text>.*)<\/a>/;
// 执行
const result = reg.exec(str);
console.log(result);
// console.log(result[1]);
// console.log(result[2]);
console.log(result.groups.url);
console.log(result.groups.text);

P56-ES9 正则扩大 - 反向断言

从后向前匹配

// 申明字符串
let str = "JS12345 你晓得么 555 啦啦啦";
// 正向断言
// const reg = /\d+(?= 啦)/;
// const result = reg.exec(str);
// 反向断言
const reg = /(?<= 么)\d+/;
const result = reg.exec(str);
console.log(result);

P57-ES9 正则扩大 -dotAll 模式

代替换行符

// dot . 元字符, 代表除换行符以外的的任意单个字符
let str = `
    <ul>
      <li>
        <a> 肖申克救赎 </a>
        <p> 日期:1998-1-1</p>
      </li>
      <li>
        <a> 阿甘正传 </a>
        <p> 日期:1998-1-1</p>
      </li>
    </ul>`;
// 申明正则
// const reg = /<li>\s+<a>(.*?)<\/a>\s+<p>(.*?)<\/p>/;
const reg = /<li>.*?<a>(?<title>.*?)<\/a>.*?<p>(?<time>.*?)<\/p>/gs;
// 执行匹配
// const result = reg.exec(str);
// console.log(result);
let result;
let data = [];
while ((result = reg.exec(str))) {data.push({ title: result.groups.title, time: result.groups.time});
}
// 输入后果
console.log(data);

P58-ES10 对象扩大办法 Object.fromEntries

将二维数组变成对象

// 二维数组 数组变对象
// const result = Object.fromEntries([//   ["name", "gavin"],
//   ["object", "Java, 大数据, 前端"],
// ]);
// console.log(result);
// Map
// const m = new Map();
// m.set("name", "GVIGU");
// const result = Object.fromEntries(m);
// console.log(result);
// Object.entries ES8 对象变数组
const school = {
  name: "尚硅谷",
  Object: "java",
};
const arr = Object.entries(school);
console.log(arr);

P59-ES10- 字符串办法扩大

trim 清空格

let str = "i am gavin";
console.log(str);
console.log(str.trim());
console.log(str.trimStart());
console.log(str.trimEnd());

P60-ES10 数组办法扩大 flat 和 flatMap

将数组扁平化,脱壳

// flat 参数为深度,是个数字
// const arr = [1, 2, 3, [4, 5, 6, [7, 8, 9]]];
// console.log(arr.flat(1));
// flatMap 相当于先 Map 后 flat
const arr = [1, 2, 3, 4, 5, 6];
const result = arr.flatMap((item) => [item * 10]);
console.log(result);

P61- 创立 Symbol 的 description

创立 Symbol 形容

// 创立 Symbol
let s = Symbol("尚硅谷");
console.log(s.description);

P62-ES11-class 公有属性

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.#weight);
  }
}
const girl = new Person("小绿", 12, "50kg");
console.log(girl);
// console.log(girl.#age);
girl.intro();

P63-ES11-Promise.allSettled 办法

// 申明两个 promise
const p1 = new Promise((resolve, reject) => {setTimeout(() => {resolve("少了 p1");
  }, 1000);
});
const p2 = new Promise((resolve, reject) => {setTimeout(() => {// resolve("少了 p2");
    reject("error");
  }, 1000);
});
// 调用 allSettled 办法,返回具体 Promise 对象
const result = Promise.allSettled([p1, p2]);
console.log(result);
// all 只在都胜利后返回
const res = Promise.all([p1, p2]);
console.log(res);

P64-ES11-String.matchAll

★ 十分实用, 用来失去正则批量匹配后果

let str = `
      <ul>
        <li>
          <a> 肖申克救赎 </a>
          <p> 日期:1998-1-1</p>
        </li>
        <li>
          <a> 阿甘正传 </a>
          <p> 日期:1965-1-1</p>
        </li>
      </ul>
    `;
const reg = /<li>.*?<a>(?<title>.*?)<\/a>.*?<p>(?<time>.*?)<\/p>/gs;
const result = str.matchAll(reg);
// console.log(result);
// for (let v of result) {//   console.log(v);
// }
const arr = [...result];
console.log(arr);

P65-ES11- 可选链操作符

★ 实用,可用来简化判断

// ?.
function main(config) {
  // const dbHost = config && config.db && config.db.host;
  const dbHost = config?.db?.host;
  console.log(dbHost);
}
main({
  db: {
    host: "localhost:3000",
    username: "root",
  },
});

P66-ES11- 动静 import

动静引入,懒加载

// 返回值为 promise 对象,懒加载
import("./hello.js").then((module) => {module.hello();
});

P67-ES11-BigInt 类型

用来超大数值运算

// 大数值运算
let max = Number.MAX_SAFE_INTEGER;
console.log(max);
console.log(max + 1);
console.log(max + 2);

console.log(BigInt(max));
console.log(BigInt(max) + BigInt(1));
console.log(BigInt(max) + BigInt(2));

P68- 相对全局对象 globalThis

始终指向全局对象

退出移动版