问答详情
源自:2-10 迭代器

不是很理解 这个each 求解

callback.call(context || null ,obj[i],arg)

context 是 this obj[i] 是数组的元素

arg 是什么? 有什么作用啊


提问者:qq_風 2019-08-22 10:21

个回答

  • qq_鸭会飞_0
    2019-11-28 18:11:00

    arg是传入的参数,就是‘aaa’

  • qq_風
    2019-08-22 10:28:26

    <!DOCTYPE HTML>

    <html>

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <script src="../jquery-2.1.0.js" type="text/javascript"></script>

    <title></title>

    </head>

    <body>

        


    <table border="1">

    <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>

    <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>

    <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>

    </table>


    <ul>

    <li>list item 1</li>

    <li>list item 2</li>

    <li>list item 3</li>

    <li>list item 4</li>

    <li>list item 5</li>

    </ul>



    <!-- <script type="text/javascript">


      $("td:eq(2)").css("color", "red")



      $('li').eq(2).css('background-color', 'red');

      $('li').eq(-2).css('background-color', 'pink');


    </script> -->


    <script type="text/javascript">


    function each(obj, callback, context, arg) {

        var i = 0;

    var value;

    var length = obj.length;

    for (; i < length; i++) {

    arg = i;

    callback.call(context || null, obj[i], arg);

    }

    }


    var arr = ['a', 'b', 'c'];


    each(arr, function(name, arg) {

    console.log(arg) //相当于索引

    $('body').append('<li>' + name + '</li>')

    }, this, 'aaa')



    </script>

    </body>

    </html>