首页 > 代码库 > 数组迭代

数组迭代

**1.数组迭代**
    1.遍历数组分四种,每种效率不同
      var arr=[["a","b","c"],[1,2,3]];
      A:for  ES5
      B:for of ES6
      C.forEach() 写法与其他不同,例如:arr.forEach(function(item,index){
                                     console.log(item,index);
                                      });

                               转化成箭头函数写法为:arr1.forEach((item,index)=>{
                                                          console.log(item,index)
                                                        });
     D.for in 效率最低
    
    2.返回一个新的数组
      1.map() 按顺序让数组每一项依次执行某种相同的操作 ,然乎返回一个新数组
        var arr1=[[1,2,3],[4,5,6]];
        例如:var newArr=arr1.map((item,index)=>{
              return index*2;
              })
              console.log(newArr);

      2.filter() 按顺序依次执行某种相同的操作,然后筛选出符合条件的元素,组成新数组并返回 
        例如:var newArr=arr1.filter((item,index)=>{
             return item % 2===0;
               })
             console.log(newArr);

     3.返回最终值

       1.reduce()按顺序 让前项和后项做某种计算,返回最终值.
        例如:var newArr=arr1.reduce((prev,next)=>{
             return prev+next;
              });
             console.log(newArr);
   
    4.返回一个布尔值
      1.every()一假必假
        var result=arr1.every((item,index)=>{
        return item % 2==0;
        })
       console.log(result);==>false


      2.some()一真必真
        var result=arr1.some((item,index)=>{
        return item % 2==0;
        })
       console.log(result);==>true

数组迭代