jQuery

How to loop through array with jQuery.each()?

In this tutorial, we are going to see how to loop through array with jQuery.each()? The JQuery.each() or $.each() method can be used to iterate transparently over any collection, whether it is an object or an array. Since the $.each() function gets and internally uses the “length” property of the passed array or object. So if you have a property called “length” – eg. {en: ‘english’, length: 7} – the function may not work correctly.
 

How to loop through array with jQuery.each()?
<!DOCTYPE html>
<html>
<head>
<title>Loop through array with jQuery.each()</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var colors = ["Blue", "Red", "Orange", "Green", "Blue"];
        $.each(colors, function(index, value){
            $("#colors").append(index + ": " + value + '<br>');
        });
    });
</script>  
</head> 
<body>
    <div id="colors"></div>
</body>
</html>

Output:

0: Blue
1: Red
2: Orange
3: Green
4: Blue
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *