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
  • 相关阅读:
    纯真IP数据库格式详解
    iframe框架详解
    搜刮的网址
    Drupal设置首页默认内容
    PHP开发之路之一WAMP的安装和配置
    PHP中json序列化后中文的编码显示问题
    Mysql转化blob为可读
    使用Xtrabackup来备份你的mysql
    MySQL压力测试工具mysqlslap的使用
    Cacti 监控 MySQL
  • 原文地址:https://www.cnblogs.com/mengfangui/p/9504291.html
Copyright © 2011-2022 走看看