Q:

How to display all items or values in an array using loop in jQuery

0

How to display all items or values in an array using loop in jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery.each() function

The jQuery.each() or $.each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $.each() function internally retrieves and uses the length property of the passed array or object. So, if you it has a property called length — e.g. {en: 'english', length: 5} — the function might not work properly.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Print Array Values with Loop</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function(){
        var fruitsArray = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
        $.each(fruitsArray, function(index, value){
            $("#result").append(index + ": " + value + '<br>');
        });
    });
</script>  
</head> 
<body>
    <div id="result"></div>
</body>
</html>

Similarly, you can print contents of an object through a loop, as shown below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Display Object Contents with Loop</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function(){
        var supercarObject = {"brand": "Lamborghini", "model" : "Huracan", "origin": "Italy"};
        $.each(supercarObject, function(key, value){
            $("#result").append(key + ": " + value + '<br>');
        });
    });
</script>  
</head> 
<body>
    <div id="result"></div>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to get number of elements in a div using jQuer... >>
<< How to assign block of HTML code to a JavaScript v...