ES6学习笔记2

目录

模块化

前提条件

导出-export

导出一个

导出多个

导出默认

导入-import

导入一个

导入多个

导入默认

导入合并默认

导入所有以及as关键字

可迭代对象

Set

特点

初始化

常用方法

利用set特性完成数组去重

WeakSet

Map

特点

初始化

方法

WeakMap

for of

方法

Promise

解决回调地狱

实现网络请求

Promise.all()

Promise.race()


ES6 中有 class 语法。值得注意是,这里的 class 不是新的对象继承模型,它只是原型链的语法糖表现形式。

函数中使用 static 关键词定义构造函数的的方法和属性

    class Animal {
        constructor(name, type) {
            this.name = name;
            this.type = type;
        }
        yiel() {
            console.log(this.name + "咆哮");
        }
    }
    console.log(typeof (Animal));//function

    class Cat extends Animal {
        constructor(name, color) {
            super(name, "cat");
            this.color = color;
        }
        skill() {
            console.log(`我是${this.color}的${this.name}`);
        }
    }
    var kitty = new Cat("豆奶", "黄色");
    kitty.skill();//我是黄色的豆奶
    kitty.yiel();//豆奶咆哮

模块化

前提条件

  1. 文件打开必须是http协议,不能是D: f: file协议
  2. <script type="module"></script>

导出-export

导出一个

export {name}

var name = "Mewow";
export {name}

导出多个

export {name,fun}

var name = "Mewow";
function fun() {
    console.log("贴纸上有只猫在说 干得" + name);
}
export {name,fun}

导出默认

一个文件里只能导出一个默认

export default Cat

class Cat {
    constructor(name) {
        this.name = name;
    }
}
export default Cat;

导入-import

导入一个

import {name} from url

import {name} from './js/utils.js'
console.log(name);//Mewow

导入多个

import {name,fun} from url

import {name,fun} from './js/utils.js'
console.log(name);//Mewow
fun();//贴纸上有只猫在说 干得Mewow

导入默认

import Cat from url

import Cat from './js/utils.js';
var kitty=new Cat("豆奶");
console.log(kitty.name);//豆奶

导入合并默认

import Cat,{name,fun} from url

    import Cat,{name,fun} from './js/utils.js'
    console.log(name);//Mewow
    fun();//贴纸上有只猫在说 干得Mewow
    var kitty=new Cat("豆奶");
    console.log(kitty.name);//豆奶

导入所有以及as关键字

import * as utils from url

    import * as utils from './js/utils.js';
    console.log(utils.name);//Mewow
    utils.fun();//贴纸上有只猫在说 干得Mewow
    var kitty=new utils.default("豆奶");
    console.log(kitty.name);//豆奶

可迭代对象

Set

特点

  • 类数组
  • 内容不重复

初始化

var s = new Set([1, 2, 3, 2]);
console.log(s);//Set(3) {1, 2, 3}

常用方法

  • add 添加
  • delete 删除
  • clear 清空
  • has 检查是否有
  • size 长度

利用set特性完成数组去重

    var arr = [1, 2, 2, 4, 5, 1, 2, 1, 23, 8];
    arr1 = Array.from(new Set(arr));
    arr2 = [...new Set(arr)];
    console.log(arr1);//[1, 2, 4, 5, 23, 8]
    console.log(arr2);//[1, 2, 4, 5, 23, 8]

WeakSet

WeakSet结构与Set类似,也是不重复的值的集合。
WeakSet的成员只能是对象,而不能是其他类型的值

Map

特点

ES6提供了Map数据结构。它类似于对象,也是键值对的集合,但是“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键

初始化

    var m = new Map([
        ['Michael', 95],
        ['Bob', 75],
        ['Tracy', 85]
    ]);
    console.log(m);Map(3)// {'Michael' => 95, 'Bob' => 75, 'Tracy' => 85}
   

方法

  • set 添加
  • get 获取
  • has 检查是否有
  • size 长度
  • delete 删除
  • clear 清空

WeakMap

WeakMap 就是一个 Map,只不过它的所有 key 都是弱引用,意思就是 WeakMap 中的东西垃圾回收时不考虑,使用它不用担心内存泄漏问题。

另一个需要注意的点是,WeakMap 的所有 key 必须是对象。没有size

for of

for in 循环用于遍历数组,类数组或对象,ES6中新引入的for of循环功能相似,不同的是每次循环它提供的不是序号而是值。

可以被for of遍历的元素:字符串数组setmap

    var arr1 = [1, 2, 3, 4, "12"];
    for (let a of arr1) {
        console.log(a);
    }

    var arr2 = ["mewow", "meme", "喵", "妙"];
    for (a of arr2) {
        console.log(a);
    }

方法

keys()   键集合

    var arr = ["A", "B", "C", "D"];
    for (let k of arr.keys()) {
        console.log(k);
    }

values() 值的集合

    var arr = ["A", "B", "C", "D"];
    for (let v of arr.values()) {
        console.log(v);
    }

entries() 键和值的集合

    var arr = ["A", "B", "C", "D"];
    for (let a of arr.entries()) {
        console.log(a);
    }
    //遍历entries() 返回的结果为数组
    //通过数组解构可以得到值
    for (let [k, v] of arr.entries()) {
        console.log(k, v);
    }

 

Promise

ES6 对 Promise 有了原生的支持,一个 Promise 是一个等待被异步执行的对象,当它执行完成后,其状态会变成 resolved 或者rejected。

解决回调地狱

结构更清晰,没有多重嵌套

    function say(msg, time) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(msg);
            }, time);
        });
    }

    say("2s", 2000).then(res => {
        console.log(res);
        return say("3s", 3000);
    }).then(res => {
        console.log(res);
        return say("5s", 5000);
    }).then(res => {
        console.log(res);
    })

实现网络请求

例子:得到当前所在的城市和天气

 function getApi(url) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url,
                dataType: "jsonp",
                success(res) {
                    resolve(res);
                },
                error(res) {
                    reject(res);
                }
            })

        });
    }
    var url = "https://apis.map.qq.com/ws/location/v1/ip?key=3BFBZ-ZKD3X-LW54A-ZT76D-E7AHO-4RBD5&output=jsonp";
    getApi(url).then(res => {
            // console.log(res);
            var info = res.result.ad_info;
            $(".city").text(info.city);
            var url_w =
                `http://wis.qq.com/weather/common?weather_type=observe|forecast_24h|air&source=pc&province=${info.province}&city=${info.city}`;
            return getApi(url_w);
        }).then(res => {
            // console.log(res);
            $(".weather").text(`  ${res.data.observe.degree}°C  ${res.data.observe.weather}`);
        })
        .catch(err => console.error(err));

Promise.all()

此方法在集合多个 promise 的返回结果时很有用。

完成(Fulfillment):

  • 如果传入的可迭代对象为空,Promise.all 会同步地返回一个已完成(resolved)状态的promise
  • 如果所有传入的 promise 都变为完成状态,或者传入的可迭代对象内没有 promisePromise.all 返回的 promise 异步地变为完成。
  • 在任何情况下,Promise.all 返回的 promise 的完成状态的结果都是一个数组,它包含所有的传入迭代参数对象的值(也包括非 promise 值)。

失败/拒绝(Rejection):

  • 如果传入的 promise 中有一个失败(rejected),Promise.all 异步地将失败的那个结果给失败状态的回调函数,而不管其它 promise 是否完成。

Promise.race()

race 函数返回一个 Promise,它将与第一个传递的 promise 相同的完成方式被完成。它可以是完成( resolves),也可以是失败(rejects),这要取决于第一个完成的方式是两个中的哪个

  • 如果传的迭代是空的,则返回的 promise 将永远等待。
  • 如果迭代包含一个或多个非承诺值和/或已解决/拒绝的承诺,则 Promise.race 将解析为迭代中找到的第一个值。

猜你喜欢

转载自blog.csdn.net/TeAmo__/article/details/123075359