i'm currently learning about javascript. I wanted to ask about printing all array elements with looping. What kind of loop/condition i should use? can anyone give me a snippet/example how to do it? thank you.
var newObj = [
{
id : "1",
name: "one"
},
{
id : "2",
name: "two"
},
{
id : "3",
name: "three"
},
{
id : "4",
name: "four"
},
{
id : "5",
name: "five"
},
]
console.log(newObj);
window.onload = function ()
{
var x;
x = newObj[0].name;
//x = newObj[0].id;
document.getElementById("id").innerHTML = x;
};
<!DOCTYPE html>
<html>
<head>
<script src="1.js"></script>
</head>
<body>
<h3 align="center" id="id"></h3>
</body>
</html>
newObjnewObj[0]will give you the first array element, andnewObj[0].namewill give you that element's name. Combine that with a basicforloop using the loop counter instead of the hard-coded0and Bob's your uncle - not necessarily the best solution, but one that you should study till you understand it. I would be surprised if introductory JS tutorials didn't cover using a loop with an array.