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
    }
     
  • 相关阅读:
    函数调用栈的总结
    Calling convention-调用约定
    函数可以返回结构体的原因
    pthread_join/pthread_exit的用法解析
    线程退出的几种方式和资源回收【线程编程中避免内存泄漏】
    线程状态与tcb、线程的生命周期
    pthread_cleanup_push vs Autorelease VS 异常处理
    thread.h
    Thread Control Block
    线程与cpu
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/12702785.html
Copyright © 2011-2022 走看看