简体   繁体   中英

looping through an object using a for in

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>

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; 
});

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 .

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:

http://jsfiddle.net/7z0qonb3/

var text = '';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM