zoukankan      html  css  js  c++  java
  • js-jquery-数组遍历

    一、原生方法支持

    1、普通for循环

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

    说明:性能很高,但是仍可以优化。

    2、优化版for循环【推荐】

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

    说明:性能最高,使用临时变量,将长度缓存起来,避免重复获取数组长度,数组长度越大时优化效果越明显。

    3、弱化版for循环

    for(j = 0; arr[j]!=null; j++) {   
    }

    说明:严格上也属于for循环,只不过是没有使用length判断,而使用变量本身判断。

    4、foreach循环

    arr.forEach(function(value,index,array){//value:当前项  index:索引  array:原始数组
    });

    说明:

      在IE6-8下都不兼容。

      数组中有几项,那么传递进去的匿名回调函数就需要执行几次;

      理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组;

    示例:

    var arr = [12,23,24,42,1];
    var res = arr.forEach(function (item,index,input) {
         input[index] = item*10;
    })
    console.log(res);//-->undefined;
    console.log(ary);//-->[120,230,240,420,10]; 通过数组索引改变了原数组

    5、foreach变种

    Array.prototype.forEach.call(arr,function(el){     
    });

    说明:在IE6-8下都不兼容。

    6、forin循环

    for(j in arr) {   
    }

    说明:效率最低。

    7、map遍历

    arr.map(function(value,index,array){//value:当前项  index:索引  array:原始数组
    });

    说明:效率低,比不上foreach

    区别:map的回调函数中支持return返回值;return的是什么,相当于把数组中的这一项变为什么(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);

    示例:

    var arr = [12,23,24,42,1];
    var res = arr.map(function (item,index,input) {
         return item*10;
    })
    console.log(res);//-->[120,230,240,420,10]; 原数组拷贝了一份,并进行了修改
    console.log(ary);//-->[12,23,24,42,1]; 原数组并未发生变化

    8、forof遍历(需要ES6支持)

    for(let value of arr) {  
    });

    说明:是es6里面用到的,性能要好于forin,但仍然比不上普通for循环。

    一般意义上的效率:优化版for循环>普通for循环>弱化版for循环>……>forin循环|foreach变种

    二、Jquery方法

    1、$.each()方法 【推荐】

    $.each(array,function(index,value){
    })

    示例:

    var arr = [12,23,24,42,1];
    $.each(arr, function (index,item) {
         console.log(index) // 0 1 2 3 4
         console.log(item) // 12 23 24 42 1
    })

    2、$().each()方法

    在dom处理上用的比较多,如果一个html页面上面有多个checkbox,这时用$().each来处理checkbox

    示例

    $("input[type='checkbox']").each(function(index,item){
       $(this).attr("checked",true);
    });
  • 相关阅读:
    查看端口被占用
    Eclipse导入包
    Eclipse中构造方法自动生成
    Eclipse中get/set方法自动生成
    Eclipse改字体大小
    设计六原则
    类的关系
    JAVA实现多线程下载
    try...catch的前世今生
    447. 回旋镖的数量
  • 原文地址:https://www.cnblogs.com/bjlhx/p/6756688.html
Copyright © 2011-2022 走看看