• 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
    }
     
  • 相关阅读:
    python中基本类型的连接组合和互相转换13种方式
    Python中通过csv的writerow输出的内容有多余的空行两种方法
    Python中定义只读属性
    python 中的__init__.py的用法与个人理解
    python 调试大法
    python中错误、调试、单元测试、文档测试
    关于python中的增量赋值的理解
    jedis连接集群
    JSR 303
    感悟2017.3.17 星期五
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/12702785.html
Copyright © 2020-2023  润新知