i am trying to understand following fragment of javascript code
<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through the properties of an object named "person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction()
{
var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>
i am a little confused with this line
for (x in person)
{
txt=txt + person[x];
}
as i guessed it is a associative array,with key–> value relationship and as a final result should not it print like this?
fname:"John",lname:"Doe",age:25
?
thanks very much
First, there is no concept of associate arrays in JavaScript, the
personis an object and an object is iterated using thefor-inloop.The line:
simply reads each property of the
personobjects and concatenates the value in thetxtvariable giving the result:FYI, always use
for-inloop for objects and normalforloop for arrays.