foreach equivalent of php in jquery?

前端 未结 5 1627
再見小時候
再見小時候 2020-12-31 06:58

Is there a foreach code in JQuery as in PHP? I have a code in php,like

       
if(\"

        
相关标签:
5条回答
  • 2020-12-31 07:24

    The $.each function is similar.

    It allows you to iterate arrays using a callback function where you have access to each item:

    var arr = [ "one", "two", "three", "four", "five" ];
    
    
    $.each(arr, function(index, value) {
      // work with value
    });
    

    Maybe is useful to know, if you want to break the loop, you can do it with return false; or if you want to skip only one iteration (continue), you return true;

    0 讨论(0)
  • 2020-12-31 07:29

    There is jQuery.each.

    0 讨论(0)
  • 2020-12-31 07:30

    If you want to iterate an object, I would recommend the JavaScript variant:

    for (var key in obj) {
        alert(key + ': ' + obj[key]);
    }
    

    You can also iterate objects in jQuery like this:
    Note! Doing this is pretty pointless unless you think this syntax is much simpler to maintain. The below syntax has much more overhead than the above, standard JavaScript, for-loop.

    $.each(obj, function (key, value) {
        alert(key + ': ' + value);
    });
    

    To iterate arrays, this is how you do it in standard JavaScript (assuming arr is the array):

    for (var i = 0, l = arr.length; i < l; i++) {
        alert(i + ': ' + arr[i]);
    }
    

    To do it in jQuery, you can do it like this:

    $.each(arr, function (index, value) {
        alert(index + ': ' + value);
    });
    
    0 讨论(0)
  • 2020-12-31 07:34

    Jquery operating on selectors:

    $('a').each(function() {
        $(this).click(function(e) {
           e.preventDefault()
           var href = this.href;
           open(href);
        });
        // operate on the anchor node.
    });
    

    jQuery direct $.each:

    var a = ['one', 'two'];
    
    $.each(a, function() {
        alert(this)
    });
    

    JS: Vanilla for loop

     for ( var i = 0, len = 10; i<l; ++i ) {
        alert(i)
     }
    

    JS #2: vanilla for

     var humanLimbs = ['arms', 'legs'];
     for ( var limb in humanLimbs ) {
         if ( humanLimbs.hasOwnProperty(limb) ) {
            alert( limb )
         }
     }
    

    Js #3: infinite loop

    for (;;) { alert(1) } // dont try this :p
    
    0 讨论(0)
  • 2020-12-31 07:47

    Javascript supports the for(data in data_array) syntax. jQuery also has a $.each function (as already mentioned)

    0 讨论(0)
提交回复
热议问题