zoukankan      html  css  js  c++  java
  • 数组的foreach方法和jQuery中的each方法

    欢迎加入前端交流群交流知识&&获取视频资料:749539640

    /*
    * 数组的forEach方法:
    * 1、返回给回调的参数先是值,然后是下标
    * 2、回调函数执行时内部的this指向window
    * */

    1 var arr = [1,2,3,4,5];
    2 arr.forEach(function( val, index ) {
    3 console.log( val, index, this );
    4 });


    /*
    * jQ实例的each方法,
    * 1、返回给回调的参数先是下标,然后是值
    * 2、回调函数执行时内部的this就指向遍历到的每一个值(就是回调中接收到的val)
    * 3、如果想中断遍历,在回调中返回false即可
    * */

    1 $('li').each( function( index, val ) {
    2 
    3 console.log( index, val, this );
    4 
    5 if( index === 1 ) {
    6 return false;
    7 }
    8 });

    /*
    * jQ还提供了一个静态版本的each方法,供框架使用者使用
    * 1、返回给回调的参数先是下标,然后是值
    * 2、回调函数执行时内部的this就指向遍历到的每一个值(就是回调中接收到的val)
    * 3、如果想中断遍历,在回调中返回false即可
    * */

     1 var obj = { name: 'test', val: {} };
     2 var arr2 = [ 'abc', {}, 'qwer' ];
     3 
     4 $.each( obj, function( key, val ) {
     5 console.log( key, val, this );
     6 } );
     7 
     8 $.each( arr2, function( index, val ) {
     9 console.log( index, val, this );
    10 } );
  • 相关阅读:
    洛谷P3747 [六省联考2017]相逢是问候
    染色(dye)
    BZOJ1426: 收集邮票
    消息队列RabbitMQ
    CRM
    BBS
    版本控制
    RESTful API
    Luffy
    axios使用
  • 原文地址:https://www.cnblogs.com/wangzhichao/p/7865541.html
Copyright © 2011-2022 走看看