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
  • 相关阅读:
    c# list排序的三种实现方式 (转帖)
    LINQ TO SQL 中的join(转帖)
    Linq to sql 增删改查(转帖)
    DBLinq (MySQL exactly) Linq To MySql
    github
    eclipse安装github插件egit
    Android中图片的目录
    Fragment
    世界500强榜单出炉:中国公司首进三强 沃尔玛居首
    经济学,不会挣钱,更不会赚钱
  • 原文地址:https://www.cnblogs.com/mengfangui/p/9504291.html
Copyright © 2011-2022 走看看