How to Loop through the Java Script Arrays



How to iterate the data in an Array or the j son ?

Fist Let us have one simple Array with few objects inside

Example:

var states=[{"name":"Andhra Pradesh"},
{"name":"Karnataka"},
{"name":"Telangana"},
{"name":"Kerala"},
{"name":"Tamil Nadu"}
]

To display the Data we have to loop the Array . So let us use for loop for the same ;

for (var i =0;i<states.length;i++){
 document.write (states[i].name)
}

If you have multiple data values in the objects inside the array , you have to use the property of that object next to the array . For example let us add one more value to the existing Array .

var states=[{"name":"Andhra Pradesh","capital":"Amaravathi"},
{"name":"Karnataka","capital":"Bangalore"},
{"name":"Telangana","capital":"Hyderabad"},
{"name":"Kerala","capital":"Kochin"},
{"name":"Tamil Nadu","capital":"Chennai"}
]

now inside the for loop we need to add one more line as follows .


for (var i =0;i<states.length;i++){
 document.write (states[i].name);
document.write (states[i].capital);

}

Comments

Popular posts from this blog

HTML Attributes ....

How to Study Web Developement Course