zoukankan      html  css  js  c++  java
  • 常用的遍历数组,Map,Set的方法

    一,for of用法(适用iterable类型的集合即Array,Set,Map)

    var a = ['A', 'B', 'C'];
    var s = new Set(['A', 'B', 'C']);
    var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
    for (var x of a) { // 遍历Array
      console.log(x);
    }
    for (var x of s) { // 遍历Set
      console.log(x);
    }
    for (var x of m) { // 遍历Map
      console.log(x[0] + '=' + x[1]);
    }

    //数组运行结果
     A
     B
     C

    //set结构运行结果
     A
     B
     C

    //Map结构运行结果

    1=x

    2=y

    3=z

    二,使用for in

    for in遍历对象输出的是键,这也是数组,Map,Set推荐使用for of的原因

    2.1 遍历对象:

    2.2 遍历数组:

     三,forEach(Map,Set,Array适用)

    a.forEach(function (element, index, array) {
    // element: 指向当前元素的值
    // index: 指向当前索引
    // array: 指向Array对象本身
    console.log(element + ', index = ' + index);
    });

  • 相关阅读:
    STL与泛型编程-练习2-GeekBand
    HashSet
    JAVA集合
    分布式锁1 Java常用技术方案
    JAVA 锁
    JAVA多线程二
    JAVA多线程一
    Redis pipeline and list
    mongo 安装
    Intersection of Two Arrays
  • 原文地址:https://www.cnblogs.com/hyns/p/12540171.html
Copyright © 2011-2022 走看看