zoukankan      html  css  js  c++  java
  • $.each()和$().each(),以及forEach()的用法

    1.forEach() 是JS遍历数组的方法

    var arr=[1,2,3];
    arr.forEach(function(val,index,arr){
    // var 为数组中当前的值
    // index 为当前值得下标
    // arr 为原数组
    arr[index] = 2*val;
    })
    
    console.log(arr);  //结果:修改了原来数组,为每个数乘以2

    forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。

    <button onclick="numbers.forEach(myFunction)">点我</button>
    <p>数组元素总和:<span id="demo"></span></p>
    
    <script>
    var sum = 0;
    var numbers = [65, 44, 12, 4];
    
    function myFunction(item) {
        sum += item;
        demo.innerHTML = sum;
    }
    </script>

    注意: forEach() 对于空数组是不会执行回调函数的。


    在jquery中,遍历对象和数组,经常会用到$().each和$.each(),两个方法。两个方法是有区别的。

    $().each:在dom处理上面用的较多。如果页面有多个input标签类型为checkbox,对于这时用$().each来处理多个checkbook,例如:

    $("input[name='ch']").each(function(i){
    if($(this).attr('checked')==true)
    {
    //一些操作代码
    
    }

    回调函数是可以传递参数,i就为遍历的索引。

    $.each() :遍历一个数组

    $.each([{"name":"limeng","email":"xfjylimeng"},{"name":"hehe","email":"xfjylimeng"},function(i,n)
    {
    alert(“索引:"+i,"对应值为:"+n.name);
    });

    参数i为遍历索引值,n为当前的遍历对象.

    var arr1 = [ "one", "two", "three", "four", "five" ];
    $.each(arr1, function(){
    alert(this);
    });
    输出:one   two  three  four   five
    var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    $.each(arr2, function(i, item){
    alert(item[0]);
    });
    输出:1   4   7
    var obj = { one:1, two:2, three:3, four:4, five:5 };
    $.each(obj, function(key, val) {
    alert(obj[key]);
    });
    输出:1   2  3  4  5

    参考链接:http://www.frontopen.com/1394.html   https://www.cnblogs.com/longailong/p/6409172.html

  • 相关阅读:
    Springboot + Caffeine 实现本地缓存
    springboot + mybatis-plus + sharding-jdbc 实现单库分表
    工厂模式+策略模式 使用
    JAVA 金额自动除以100,精确到分
    spring aop + 自定义注解实现本地缓存
    springboot 使用 retry重试机制
    Mybatis-plus 自动注入公共字段
    docker 安装kafka
    ES 实现聚合分页
    Authentication token manipulation error 及 mongodb WiredTigerLAS.wt 文件过大问题
  • 原文地址:https://www.cnblogs.com/wuss/p/10523502.html
Copyright © 2011-2022 走看看