2

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

始终指向全局对象


悠悠江水
33 声望0 粉丝

一路前进,一路成长,终身学习


下一篇 »
vue安装sass