zoukankan      html  css  js  c++  java
  • 彻底弄明白 for循环、forEach、for in 、for of 、map、filter的用法及区别

    1、for循环:for循环是成熟且稳定的JS语法,可以很多复杂的环境中运行,当大量数据及复杂逻辑的时候,for循环性能最佳,它能通过每个属性的 i 去针对性查找

      let arr1=[1,2,3,4,5,6]
      let newArr=[]
    
    
    // for循环
        for(let i=0;i<arr1.length;i++){
            newArr.push(arr1[i]*2)
        }

    输出结果

    2、for..in..:也是JS循环的一种,但是性能很低效,因为它会遍历数组里的每一个属性,包括不知名或者动态添加的属性,全部查找遍历的内存开销很大,所以再开发尽量不要用for in 

     let arr1=[1,2,3,4,5,6]
        let newArr=[]
    
    //for in 
        for(let x in arr1){
            newArr.push(arr1[x]*2)
        }

    输出结果:

    3、for...of...

        let arr1=[1,2,3,4,5,6]
        let newArr=[]
        //for of
        for(let item of arr1){
            newArr.push(item*2)
        }

    输出结果:

    4、forEach:不会返回结果,必须要通过外部数组push

        let arr1=[1,2,3,4,5,6]
        let newArr=[]
    
        //forEach:不会返回一个结果,而是undiefund
        arr1.forEach(item=>{  
            newArr.push(item*2)
        })

    输出结果:

    5、map:返回一个新数组,它不会检测一个空数组,也不会改变原始数组

        let arr1=[1,2,3,4,5,6]//map:map返回一个新的数组,不会检测空数组,也不会改变原始数组
        let newArr=arr1.map((item)=>{
            return item*2
        })
        

    输出结果:

    6、filter:遍历过滤,它不会对空数组进行检测,也不会改变原始数组,它能通过筛选条件快速给出遍历结果,不符合条件的就不会去遍历,符合条件的才会遍历,极大的节省了遍历开销成本

        let arr1=[1,2,3,4,5,6]
    
        function filterFN(num){
            return num>3
        }
        let newArr=arr1.filter(filterFN)

    筛选结果:

     具体的业务场景,用最合适方法

  • 相关阅读:
    [转]Maven类包冲突终极三大解决技巧
    python chardet 模块
    python pretty-errors模块
    认识执行时机
    python对象销毁顺序
    python字符串驻留
    python绘图练习
    小练习2
    小练习
    4G 内存处理 10G 大小的文件
  • 原文地址:https://www.cnblogs.com/xxflz/p/12889183.html
Copyright © 2011-2022 走看看