• $.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

  • 相关阅读:
    最小生成树(Prim和Kruscal)
    SPFA(还是稍微写写吧,虽然没什么用)
    最短路径(随便写写)(Floyd,Bellman-Ford,Dijkstra)
    Just a Hook HDU
    数论逆元
    最长上升子序列(LIS)算法(附Codeforces Round #641 (Div. 2),B题题解)
    Educational Codeforces Round 86 (Rated for Div. 2)
    Codeforces Round #633 (Div. 2)
    Codeforces Round #631 (Div. 2)
    Mayor's posters(线段树离散化)
  • 原文地址:https://www.cnblogs.com/wuss/p/10523502.html
Copyright © 2020-2023  润新知