In jquery, we commonly use the two methods $().each and $.each() to traverse arrays. The two methods $().each and $.each() seem to be similar on the surface. , However, in fact, there are differences between these two methods. Both methods show their own characteristics for different operations. The following article will introduce to you how jquery uses the two methods $().each and $.each() to implement array traversal.
Let’s not say much, let’s go directly to the text~
1. jquery’s method of traversing an array $().each
For $ The ().each method is often used in DOM processing, such as the following example:
$('.list li').each(function(i, ele) { console.log(i, ele); // console.log(this == ele); // true $(this).html(i); if ($(this).attr('data-item') == 'do') { $(this).html('data-item: do'); }; })
i: sequence value ele: only the DOM element currently being traversed
this is currently being traversed For traversed DOM elements, jQuery methods cannot be called
$(this) == $(ele). For the jquery object of the currently traversed element, jquery methods can be called for DOM operations
2. The jquery method of traversing an array, $.each
, has no return value. The supported anonymous function has 2 parameters: if the array is traversed, i is the index of the current item, and n is the index of the current item in the array. The current item
example is as follows:
//数组:i为索引,n为值 $.each( [1,2,3,4], function(i, n){ console.log( i + ": " + n ); });
What needs to be noted here is:
Use return or return true to skip a loop and continue executing the subsequent loop.
Use return false to terminate the execution of the loop, but not terminate the function execution.
You cannot use break and continue to skip loops. $(this) in
$.each is different from this, but the traversal result is the same.
This article ends here. For more information about jquery traversal, please refer tojquery manualfor further understanding.
The above is the detailed content of How to traverse an array in jquery? Two commonly used ways to traverse arrays in jquery. For more information, please follow other related articles on the PHP Chinese website!