ES6 Iterator、Generator

介绍

本文是在学习ES6时做的一些学习笔记,所有的笔记请查看:ES6 学习笔记

Iterator

Iterator是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即一次处理该数据结构的所以成员)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Iterator</title>
</head>
<style>

</style>

<body>
<script>
// Array 补充的values方法
Array.prototype.values = function(){
    let i = 0;
    let items = this;
    
    return{
        next(){
            const done = i>items.length;
            const value = done?undefined:items[i++];
            return {
                value;
                done
            }
            
        }
    }
}
const colors=['red','blue','green']
// entries() Array自带的方法
const iterator=colors.entries();// 返回数组的遍历器iterator
iterator.next() //返回第一个数组元素,该元素包含索引和其对应的值

//keys()  Array自带的方法
const iterator = colors.keys()// 返回colors索引值
iterator.next()  //返回colors的第一个索引值 0


//values() 补充
const iterator = color.values()//返回colors的值
iterator.next() //返回colors第一个值 red
</script>

</body>
</html>

Generator:

生成器是一种返回迭代器的函数,通过function关键字后的星号(*)来表示,函数中会用到新的关键字yield。星号可以紧挨着function关键字,也可以在中间添加一个空格

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Generator</title>
</head>

<body>
<script>
function* listColors(){
    yield 'red';
    yield 'green';
    yield 'blue';
}

function* listColorsindex(){
    let i;
    yield i;
    i++;
    yield i;
    i++;
    yield i;
}

//调用生成器函数
const color=listColrs();
color.next(); // 调用next()方法获取值  red
color.next(); // green
color.next(); // blue

const colorindex=listColorsindex();
colorindex.next() // 0
colorindex.next() // 1
colorindex.next() // 2

const owners = [
    {name: 'mojombo',location: 'San Franciso', followers: 123},
    {name: 'vanpelt',location: 'Bay Minette', followers: 1034}.
    {name: 'wycats',location: 'Los Angeles,CA', followers: 388}
]

function* loop(arr){
    for(let owner of arr){
        yield owner;
    }
}
const ownersloop=loop(owners);
ownersloop.next() // 返回  {name: 'mojombo',location: 'San Franciso', followers: 123}


</script>

</body>
</html>

Generator 应用:控制ajax工作流

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spread operator Intro</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
<script>
function ajax(url){
    axios.get(url).then(res => userGen.next(res.data));
    // userGen.next(res.data)操作会将ajax操作返回的值存入users中保存
    // 作为下一步操作的数据使用。
}
function* step(){
    const users=yield ajax('https://api.github.com/users');
    const firstUser=yield ajax(`https://api.github.com/users/${users[0].login}`)
    const followers=yield ajax(firstUser.followers_url);
}
const userGen = steps();
userGen.next() 

</script>

</body>
</html>
发布了25 篇原创文章 · 获赞 18 · 访问量 991

猜你喜欢

转载自blog.csdn.net/MoonNight608/article/details/104284167