ES6 learning(入门)第三记

JavaScript 2020-02-02 144 次浏览 次点赞

循环对象

可迭代的对象

迭代的方法

let list = [10, 20, 30];
let str = '你好哦';
let map = new Map();
map.set('JS', 'JavaScript');
map.set('P', 'PHP');
map.set('PY', 'Python');

for(let val of list) {
    console.log(val);
}

for(let val of str) {
    console.log(val);
}

for(let [key, value] of map) {
    console.log(key, value);
}
循环对象1.png
let item = map.value();
let temp;
while(temp = item.next()) {
    if(temp.done){
        break;
    }else {
        console.log(temp);
    }
}
循环对象2.png

可迭代的对象

制作一个可迭代的对象

Symbol.iterator

class Player {
    constructor(list) {
        this.list = list;
    }
    [Symbol.iterator]() {
        let current = 0;
        let that = this;
        return {
            next() {
                return current < that.list.length ? {value: that.list[current++], done: false} : { done: true };
            }
        }
    }
}
let player = new Player(['fm', 'fj', 'cu']);
for (let temp of player) {
    console.log(temp);
}
可迭代的对象.png

简单迭代生成器

function* {} 迭代生成器

yield:迭代返回

function* generator() {
    yield 'f';
    yield 'm';
    yield 'j';
    yield 'i';
    yield 'e';
}

for(let val of generator()) {
    console.log(val);
}
简单迭代1.png
function* countdown(begin) {
    while(begin > 0) {
        yield begin--;
    }
}

for(let temp of countdown(5)) {
    console.log(temp);
}
简单迭代2.png

简单迭代类

建立一个简单的迭代类

class MyList {
    constructor(list) {
        this.list = list;
        this[Symbol.iterator] = function* () {
            let current = 0;
            let that = this;
            while (current < that.list.length) {
                yield that.list[current++];
            }
        }
    }
}

let mylist = new MyList([10, 20, 30]);
for (let val of mylist) {
    console.log(val);
}
简单迭代类.png

模块化设计

建立一个模块

调用模块功能

  • Player.mjs
class Player {
    constructor(name) {
        this.name = name;
    }
    sayHello() {
        console.log(`Hello ${this.name}`)
    }
}

export default Player;
  • main.mjs
import Player from './Player.mjs';

let curry = new Player('curry');
curry.sayHello();
类模块设计.png
ES6入门系列说明:本系列仅仅作为ES6入门教学视频的归纳总结与记录,在此感谢小马视频ORYouTube地址

本文由 fmujie 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论

召唤看板娘