zoukankan      html  css  js  c++  java
  • js中数组遍历的几种方法及其区别

    参考网站:

    http://www.cnblogs.com/lvmh/p/6104397.html

    第一种最常用的:for循环

     for(j = 0; j < arr.length; j++) { }

     优化版for循环

    for(j = 0,len=arr.length; j < len; j++) {
       
    }

     对于数组较大时,优化比较明显;

     第二种:foreach

    arr.forEach(function(e){  
       
    });

    第三种:for ……in

      

    var arr = new Array("first", "second", "third") 
    for(var item in arr) {
    document.write(arr[item]+",");
    }

       for……in 的效率比较低

    第四种:map 遍历

    arr.map(function(n){  
       
    });

    第五种:for……of 遍历(需要ES6支持)

       

    for(let value of arr) {  
       
    });

      

    for、map是比较常用的两种方法,性能也还行。

    关于跳出循环的几种方式:

    • return ==》结束循环并中断函数执行;
    • break ==》结束循环函数继续执行;
    • continue ==》跳过本次循环;
    • for 循环中的变量 i,由于 ES5并没有块级作用域的存在,它在循环结束以后仍然存在于内存中,所以建议使用函数自执行的方式来避免;
  • 相关阅读:
    Attributes in C#
    asp.net C# 时间格式大全
    UVA 10518 How Many Calls?
    UVA 10303 How Many Trees?
    UVA 991 Safe Salutations
    UVA 10862 Connect the Cable Wires
    UVA 10417 Gift Exchanging
    UVA 10229 Modular Fibonacci
    UVA 10079 Pizza Cutting
    UVA 10334 Ray Through Glasses
  • 原文地址:https://www.cnblogs.com/zk666/p/6840897.html
Copyright © 2011-2022 走看看