javascript forEach方法与jQuery each区别

1、forEach方法

语法:

array.forEach(function(currentValue, index, arr), thisValue)

参数:

示例:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>forEach方法</title>
    </head>

    <body>
        <script type="text/javascript">
        var num = [2,1,3];
        num.forEach(function(currentValue,index,arr){
            console.log("当前值:"+currentValue+"当前索引:"+index);
        });
        
        </script>
    </body>

</html>

控制台输出为:

2、each方法

语法:

jQuery.each( collection, callback(indexInArray, valueOfElement) )

参数:

回调函数的第一个参数为indexInArray(索引值),第二个参数valueOfElement(值)

示例:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>each方法</title>
    </head>

    <body>
        <!--注意src路径要对-->
        <script src="js/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            var num = [2, 1, 3];
            $.each(num, function(index, currentValue) {
                console.log("当前值:" + currentValue + "当前索引:" + index);
            });
        </script>
    </body>

</html>

控制台输出为:

总结:forEach与each的参数(尤其是index与value)的位置不一样。


延伸:jQuery的map方法的参数列表:

jQuery.map( array, callback(elementOfArray, indexInArray) )

示例:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>map方法</title>
    </head>

    <body>
        <!--注意src路径要对-->
        <script src="js/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            var arr = ["a", "b", "c", "d", "e"];
            arr = jQuery.map(arr, function(value, index) {
                return(value.toUpperCase() + index);
            });
            console.log(arr);
        </script>
    </body>

</html>

控制台输出为:



原文地址:https://www.cnblogs.com/mengfangui/p/7965463.html