Server returns to the client this JSON:
{
"comments": [
{
"id": 99,
"entryId": 19,
"author": "Вася",
"body": "Комент Васи",
"date": "20.10.2022"
},
{
"id": 100,
"entryId": 19,
"author": "n54",
"body": "w754",
"date": "21.10.2023"
}
],
"admin": false
}
I am trying to show out it:
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var json = eval("("+xmlhttp.responseText+")");
for(var comment in json.comments){
alert(comment["author"]);
}
}
As expected, cycle works 2 times, but this alert shows only "undefined". But if I try to execute alert(json.admin); it will show false, as planned. What am I doing wrong?
If you have to iterate over the contents in the array you should iterate over the array indexes rather than iterate over the properties in the array,
So use the following code snippet to iterate over the array indexes which is the right thing to do,
for(var i = 0; i < json.comments.length; i++){
alert(json.comments[i]["author"]);
}
Iterating over array properties like the following code snippet is not the right way because one of the array properties contains 'remove' function.
for(var i in json.comments){
alert(json.comments[i]["author"]);
}
In the above code i will take values 0, 1, 2,..., remove function