Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6打卡处 #2

Open
moyahuang opened this issue Mar 24, 2020 · 1 comment
Open

ES6打卡处 #2

moyahuang opened this issue Mar 24, 2020 · 1 comment

Comments

@moyahuang
Copy link
Owner

moyahuang commented Mar 24, 2020

2020/03/24 iterator和for...of循环

遍历器对象实质是指针对象(保存一个指针以及next方法以移动指针位置)

  • 可遍历:有[Symbol.iterator]属性的对象
    • 该属性值为遍历器对象生成函数
    • 原生具备该接口的数据结构包括Set, Map, Array, String, TypedArray, 函数arguments对象,NodeList对象
obj[Symbol.iterator]=function(){//一个简单的遍历器对象生成函数
    var index=0;
    return{
        next:function(){
            if(index<3){
                index++;
                return {value:index,done:false};
            }else{
                return {done:true};
            }

        }
    }
}
  • 作用:提供统一的遍历接口(.next()移动指针,返回对象{value:value, done: true/false}
  • 调用场合
    • for...of会自动遍历具备该接口的数据结构
    • 解构赋值
    • 扩展运算符
    • yield*
    • Array.from()
      forEach vs. for...in vs. for...of
      forEach无法中途跳出循环
      for...in遍历所有键名,仅适用于对象
      for...of在遍历数组时不会输出非数字键,可用于任何iterable对象
@moyahuang
Copy link
Owner Author

moyahuang commented Mar 25, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant