zoukankan      html  css  js  c++  java
  • ES6 for...of循环

    1、for of

    const arr = ['red', 'green', 'blue'];
    
    for(let v of arr) {
      console.log(v); // red green blue
    }

    for...of循环可以代替数组实例的forEach方法。

    const arr = ['red', 'green', 'blue'];
    
    arr.forEach(function (element, index) {
      console.log(element); // red green blue
      console.log(index);   // 0 1 2
    });

    JavaScript 原有的for...in循环,只能获得对象的键名,不能直接获取键值。ES6 提供for...of循环,允许遍历获得键值。

    var arr = ['a', 'b', 'c', 'd'];
    
    for (let a in arr) {
      console.log(a); // 0 1 2 3
    }
    
    for (let a of arr) {
      console.log(a); // a b c d
    }

    上面代码表明,for...in循环读取键名,for...of循环读取键值。如果要通过for...of循环,获取数组的索引,可以借助数组实例的entries方法和keys方法.

    for of:不同于forEach方法,它可以与breakcontinuereturn配合使用

     

     2、for in的缺陷

    for in会遍历出原型对象以及对象本身属性值。

    Object.prototype.objCustom = function() {}; 
    Array.prototype.arrCustom = function() {};
    
    var arr = [3, 5, 7];
    arr.foo = 'hello';
    
    for (var i in arr) {
       console.log(i);
    }
    // 结果是:
    // 0
    // 1
    // 2
    // foo
    // arrCustom
    // objCustom
    Object.prototype.objCustom = function() {}; 
    Array.prototype.arrCustom = function() {};
    
    var arr = [3, 5, 7];
    arr.foo = 'hello';
    
    for (var i in arr) {
       if (arr.hasOwnProperty(i)) {
        console.log(i);
      }
    }
    // 结果是:
    // 0
    // 1
    // 2
    // foo

    3、foreach的缺陷

     遍历数组时 无法break或者return false

    var arr = [3, 5, 7];
    
    arr.forEach(function (value) {
      console.log(value);
      if (value == 5) {
        return false;
      }
    });
    // 结果是:
    // 3
    // 5
    // 7
  • 相关阅读:
    htmilunit-- 针对抓取js生成的数据
    httpClient get方式抓取数据
    post方式的数据抓取
    利用win10自带的系统配置禁止开机启动项和程序
    linq中怎么实现多条件关联的左右连接
    win10提示管理员已阻止你运行此应用,如何强制运行
    远程连接SQL Server 2014遇到的问题和解决
    eclipse中删除多余的tomcat server
    resultMap之collection聚集
    empty()和remove()的区别
  • 原文地址:https://www.cnblogs.com/mengfangui/p/9504291.html
Copyright © 2011-2022 走看看