• ES6 - for...of


    for...of是一种用来遍历数据结构的方法,可遍历的对象包括:数组,对象,字符串,节点数组等

    我们先来看一下现在存在的遍历方式:

    var arr=[1,2,3,4]

    (1)for循环

    缺点:代码不够简洁

    (2)forEach():  arr.forEach(function(value,index) {...});

    缺点:无法中断循环

    (3)for..in:我们常用来遍历对象属性

      for (let i  in arr){...}

     缺点:每次循环得到的是字符串类型,而不是数字类型。

    之后,我们来看一下ES6 的for...of

    for (let value of arr ){...}

    (1)终止循环(break),跳过循环(continue)

    for (let value of arr ){

      if(value==3){

        break;

      }

      console.log(value)   //1 2

    }

     

    for (let value of arr ){

      if(value==3){

        continue;   //跳过当前循环

      }

      console.log(value)   //1 2 4 5 

    }

     (2)得到数字类型的索引   keys()

    for (let index of arr.keys() ){

      console.log(index)   // 0 1 2 3 4 

    }

    keys() 为数组的扩展,表示获取键名再遍历

    (3)遍历多种类型的数据结构

    • 字符串遍历

      var str='hello';

      for (let v of str){

        console.log(v)    // h e l l o

      }

    • DOM节点遍历

      <li>1</li>

      <li>2</li>

      <li>3</li>

      var lis=document.getElementsByTagName('li');

      for (let li of lis){

        console.log(li)   //<li>1</li>  <li>2</li>  <li>3</li>

      }

     

  • 相关阅读:
    COCI2013-2014 Contest#3 F 单调栈
    Topcoder SRM568 Div1 DisjointSemicircles (二分图染色)
    COCI2013-2014 Contest#1 F SLASTIČAR
    TopCoder SRM 561 Orienteering(树形dp)
    COCI20122013 Contest#5 F
    2016 多校5 ATM
    2014多校6 Another Letter Tree
    HAOI2015 数组游戏
    [CCO 2017]接雨滴
    Luogu P6789 寒妖王
  • 原文地址:https://www.cnblogs.com/telnetzhang/p/5784346.html
Copyright © 2020-2023  润新知