Reputation: 1
Can anyone help me?be stuck for a while, all i need to do is print out the properties of my object,anyone know why this doesnt work?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function person(name, dateOfBirth, nationality){
this.name = name;
this.dateOfBirth = dateOfBirth;
this.nationality = nationality;
}
var mark = new person("mark oshea",25,"irish");
var text = "";
for(x in mark) {
text += mark[x];
}
</script>
</body>
</html>
Upvotes: 0
Views: 51
Reputation: 906
Your text variable is trapped in the scope of your for loop. Adding this line outside of the for loop solves it, as demonstrated in this fiddle:
var text = '';
Upvotes: 0
Reputation: 53
Your html is missing closing/opening elements, and you were not declaring the 'var text'. Try it like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Person</h1>
<p id="person"></p>
<script type="text/javascript">
function person(name, dateOfBirth, nationality){
this.name = name;
this.dateOfBirth = dateOfBirth;
this.nationality = nationality;
}
var text = "";
var mark = new person("mark oshea",25,"irish");
for(x in mark) {
text += mark[x] + " ";
}
var person_paragraph = document.getElementById("person");
person_paragraph.innerHTML = text;
</script>
</body>
</html>
For more info on DOM functions, I'd recommend fiddling through mdn.
Upvotes: 0
Reputation: 8165
A for ... in
loop will loop through all properties of a given array / object.
You try to access your object with the property (which you actually want).
In your case text += x;
should be what you're looking for if you want the properties.
If you want to get the values of your object you can use forEach
for example like:
mark.forEach( function(value){
text += value;
});
Upvotes: 1