zoukankan      html  css  js  c++  java
  • JavaScript 数组的遍历

    var a = [1, 2, 3];
    
    // for循环
    for(var i = 0; i < a.length; i++) {
      console.log(a[i]);
    }
    
    // while循环
    var i = 0;
    while (i < a.length) {
      console.log(a[i]);
      i++;
    }

    ES6提供三个新的方法——entries()keys()values()——用于遍历数组。它们都返回一个遍历器对象(详见《Iterator》一章),可以用for...of循环进行遍历,唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。

    for (let index of ['a', 'b'].keys()) {
      console.log(index);
    }
    // 0
    // 1
    
    for (let elem of ['a', 'b'].values()) {
      console.log(elem);
    }
    // 'a'
    // 'b'
    
    for (let [index, elem] of ['a', 'b'].entries()) {
      console.log(index, elem);
    }
    // 0 "a"
    // 1 "b"

    for ...in 遍历

    var a = [1, 2, 3];
    
    for (var i in a) {
      console.log(a[i]);
    }

    for...in不仅会遍历数组所有的数字键,还会遍历非数字键。

    var a = [1, 2, 3];
    a.foo = true;
    
    for (var key in a) {
      console.log(key);
    }
    // 0
    // 1
    // 2
    // foo

    foreach 遍历,当需要遍历数组并对每个元素进行处理时

    var colors = ['red', 'green', 'blue'];
    colors.forEach(function (color) {
      console.log(color);
    });

    map 遍历,与foreach的不同点是map可以return 

    [1,2,3].map(function (x) {
      return x * x;
    });

    参考链接:http://javascript.ruanyifeng.com/grammar/array.html

  • 相关阅读:
    jdk版本切换
    Java开发中遇到的问题
    递归删除文件夹
    重写equals方法
    JSP基础
    js把变量转换成json数据
    myBatista批量查询和插入
    Jquery密码强度校验
    Linux配置外网访问mysql
    linux下开启、关闭、重启mysql服务命令
  • 原文地址:https://www.cnblogs.com/neverleave/p/6134204.html
Copyright © 2011-2022 走看看