jqueryHow do I use jQuery to loop through each element in an array?
jQuery provides an easy way to loop through an array using the each()
function. The following example will loop through an array and print each element in the array:
var arr = ["apple", "banana", "cherry"];
$(arr).each(function( index ) {
console.log( arr[index] );
});
Output example
apple
banana
cherry
The example code above uses the each()
function to loop through the arr
array. The each()
function takes a callback function as an argument. The callback function takes two arguments, index
and value
. The index
argument is the index of the array element being processed, and the value
is the value of the array element being processed. The console.log()
method is used to print the value of each element in the array.
Code explanation
var arr = ["apple", "banana", "cherry"];
- declares an arrayarr
with three elements$(arr).each(function( index ) {
- uses theeach()
function to loop through thearr
arrayconsole.log( arr[index] );
- prints the value of each element in the array
Helpful links
More of Jquery
- How do I use jQuery ZTree to create a hierarchical tree structure?
- How do I use jQuery to zip files?
- How do I download a zip file using jQuery?
- How do I add a zoom feature to my website using jQuery?
- How do I use jQuery to zoom in or out on an element?
- How do I use jQuery to set query parameters?
- How can I use JQuery with Yii2?
- How can I get the y position of an element using jQuery?
- How can I use jQuery to check if an element is visible?
- How do I get the y-position of an element using jQuery?
See more codes...