js原生的forEach()和map()以及jquery中的each()和map()他们4者的联系和区别

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>

        $(function () {
            var arr=[1,3,5,7,9];

            var obj={0:1,1:3,2:5,3:8,4:9,length:5};
          // 利用原生的js的forEach()方法遍历
            /*
            第一个参数:当前遍历到的元素
            第二个参数:当前遍历到的索引
            原生的forEach一样不能遍历伪数组
            */
            arr.forEach(function(value,index){
                console.log(index,value);
            });


            // arr.forEach(function(value,index){
            //     console.log(index,value);
            // })

           
            // 利用jQuery的each静态方法遍历数组 
            // 它能遍历伪数组



            $.each(arr,function(index,value){
                console.log(index,value);
            })
            
        })

        //  第一个参数:当前遍历到的索引
    //  第二个参数:当前遍历到的元素


    </script>
</head>
<body>
    
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>

        $(function () {
            var arr=[1,3,5,7,9];

            var obj={0:1,1:3,2:5,3:8,4:9,length:5};
          // 利用原生的js的map方法遍历
            /*
            第一个参数:当前遍历到的元素
            第二个参数:当前遍历到的索引
            第三个参数:当前遍历到的数组
            和原生的forEach一样不能遍历伪数组
            */
            arr.map(function(value,index,arr){
                console.log(index,value,arr);
            });



            // jquery的
            /*
            第一个参数:要遍历的数组
            第二个参数:每遍历一个元素之后执行的回调函数
            回调函数的参数:
            第一个参数:遍历到的元素
            第二个参数:遍历到的索引
            */ 

            // jQuery中的each静态方法一样,map静态方法也可以遍历伪数组

         
            // $.map(arr,function(value,index){
            //     console.log(index,value);
            // });
            var res=$.map(obj,function(value,index){
                console.log(index,value);
                return value+index;
            });
            

            
            var res1=$.each(arr,function(index,value){
                console.log(index,value);
                return value+index;
            })

            // jQuery中的each静态方法和map静态方法的区别

            //  each静态方法默认的返回值就是遍历谁就返回谁
            // map静态方法返回的是一个空值

            // each的静态方法不支持在回调函数中对遍历的数组精心处理
            // map静态方法可以在回调函数中通过return对遍历的数组精心处理,然后生成一个新的数组精心返回
            
            
        })

     


    </script>
</head>
<body>
    
</body>
</html>
发布了100 篇原创文章 · 获赞 6 · 访问量 3385

猜你喜欢

转载自blog.csdn.net/weixin_43342105/article/details/104226045