Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array_name = [item1, item2, ...];
Looping Array Elements
The safest way to loop through an array, is using a for in loop:
Example(1)
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
};
for (i in myObj.cars) {
x += myObj.cars[i] + "<br>";
}
<!DOCTYPE html>
<html>
<head>
<title>How Can I Access JSON Array Values Through For In Loop</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<br>
<div class="text-center">
<h1 id="color" style="color: tomato">How Can I Access JSON Array Values Through For In Loop</h1>
</div>
<br>
<div class="well">
<h2 id="demo1"></h2>
<h2 id="demo2"></h2>
</div>
<script>
var myObj, i, x = "";
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
};
for (i in myObj.cars) {
x += myObj.cars[i] + "<br>";
}
document.getElementById("demo1").innerHTML = x;
</script>
</div>
</body>
</html>