zoukankan      html  css  js  c++  java
  • js中forEach,for in,for of循环的用法

    1. forEach遍历
    2. var array = [1,2,3,4];
          array.forEach(function(v,i){
              console.log(v,i);
          })
          array.forEach((v,i)=>{
              console.log(v,i);
          })

      一般遍历

    3.  var array = [1,2,3,4,5,6,7];  
          for (var i = 0; i < array.length; i++) {  
              console.log(i,array[i]);  
          }  

      用for in的方遍历数组

    4.  for(let index in array) {  
              console.log(index,array[index]);  
          };  

      用for in不仅可以对数组,也可以对enumerable对象操作

    5. var A = {a:1,b:2,c:3,d:"hello world"};  
      for(let k in A) {  
          console.log(k,A[k]);  
      } 

      在ES6中,增加了一个for of循环,使用起来很简单

    6. for(let v of array) {  
              console.log(v);  
          };  
      
            let s = "helloabc";  
            for(let c of s) {  
            console.log(c); 
           }

        for(let [i,v] of array.entries()) {
         console.log(i,v);
        };


      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总是得到对像的key或数组,字符串的下标,而for of和forEach一样,是直接得到值

    7. JavaScript 提供了 foreach()  map() 两个可遍历 Array对象 的方    

          forEach和map用法类似,都可以遍历到数组的每个元素,而且参数一致; 

      Array.forEach(function(value , index , array){ //value为遍历的当前元素,index为当前索引,array为正在操作的数组
        //do something
      },thisArg)      //thisArg为执行回调时的this值

      不同点:

        forEach() 方法对数组的每个元素执行一次提供的函数。总是返回undefined;

        map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。返回值是一个新的数组
      • 参数:value数组中的当前项, index当前项的索引, array原始数组;

        例子如下:

      var array1 = [1,2,3,4,5];
       
      var x = array1.forEach(function(value,index,array){
       
          console.log(value);   //可遍历到所有数组元素
       
          return value + 10
      });
      console.log(x);   //undefined    无论怎样,总返回undefined
       
      var y = array1.map(function(value,index,array){
       
          console.log(value);   //可遍历到所有数组元素
       
          return value + 10
      });
      console.log(y);   //[11, 12, 13, 14, 15]   返回一个新的数组
    8. 参考:https://www.cnblogs.com/amujoe/p/8875053.html

  • 相关阅读:
    hdu1403(后缀数组模板)
    输入外挂模板
    hdu2896(ac自动机)
    hdu2222(ac自动机模板)
    codevs1169, 51nod1084(多线程dp)
    codevs3027(dp)
    codevs1068(dp)
    大数乘法模板
    Java锁--框架
    Java并发包--ConcurrentLinkedQueue
  • 原文地址:https://www.cnblogs.com/ygyy/p/10408171.html
Copyright © 2011-2022 走看看