zoukankan      html  css  js  c++  java
  • for...of与for...in的区别

    for...of与for...in的区别

    一、总结

    一句话总结:

    for...in 语句以任意顺序迭代对象的可枚举属性。
    for...of 语句遍历可迭代对象定义要迭代的数据。
    Object.prototype.objCustom = function() {}; 
    Array.prototype.arrCustom = function() {};
    
    let iterable = [3, 5, 7];
    iterable.foo = 'hello';
    
    for (let i in iterable) {
      console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
    }
    
    for (let i in iterable) {
      if (iterable.hasOwnProperty(i)) {
        console.log(i); // logs 0, 1, 2, "foo"
      }
    }
    
    for (let i of iterable) {
      console.log(i); // logs 3, 5, 7
    }

    1、for...of语句的作用?

    for...of语句也是用来做循环的,循环可迭代对象,也就是有iterator接口的对象,比如数组、字符串、伪数组、set、map等

    1、遍历数组
    2、遍历Set
    3、遍历Map
    4、遍历字符串
    5、遍历伪数组
    等等

    二、for...of与for...in的区别

    博客对应课程的视频位置:

    无论是for...in还是for...of语句都是迭代一些东西。它们之间的主要区别在于它们的迭代方式。
    for...in 语句以任意顺序迭代对象的可枚举属性。
    for...of 语句遍历可迭代对象定义要迭代的数据。
    以下示例显示了与Array一起使用时,for...of循环和for...in循环之间的区别。

    Object.prototype.objCustom = function() {}; 
    Array.prototype.arrCustom = function() {};
    
    let iterable = [3, 5, 7];
    iterable.foo = 'hello';
    
    for (let i in iterable) {
      console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
    }
    
    for (let i in iterable) {
      if (iterable.hasOwnProperty(i)) {
        console.log(i); // logs 0, 1, 2, "foo"
      }
    }
    
    for (let i of iterable) {
      console.log(i); // logs 3, 5, 7
    }
     
  • 相关阅读:
    服务器键盘设置错误 完美解决
    windows 彻底删除360文件 360zipext.dll 等等
    VS2005智能设备中无法找到PInvoke DLL
    如何使用DotNet 2.0中的应用程序配置 Settings.settings
    维护应用程序状态(一):使用浏览器cookie
    NHibernate学习导航
    HTML基础(三):基本的HTML标签
    使用Cookie对象保存用户自定义设置
    ASP.NET2.0 个性化用户配置
    sealed修饰符的使用
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/12702785.html
Copyright © 2011-2022 走看看