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 download a zip file using jQuery?
- How do I use jQuery to change the z-index of an element?
- How do I use jQuery to detect window resize events?
- How can I get the y position of an element using jQuery?
- How can I use JQuery with Yii2?
- How do I create a jQuery Yes/No dialog?
- How do I use jQuery with Yarn?
- How do I prevent XSS attacks when using jQuery?
- How do I use jQuery to zip files?
- How can I use jQuery in WordPress?
See more codes...