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
    }
     
  • 相关阅读:
    几种基本样式,背景图,字体,下划线,行高垂直等
    网页主菜单,横向
    DOM操作
    递归的小例题
    学习两个星期后做的第一个网页
    Js的语法和循环
    JS
    75 int类型数组中除了一个数出现一次或两次以外,其他数都出现三次,求这个数。[2行核心代码]
    74 使用BitSet输出数组中的重复元素
    73 [面试题]交换一个整数的二进制表示的奇偶位(swapOddEvenBits)
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/12702785.html
Copyright © 2011-2022 走看看