简体   繁体   中英

looping over object constructors

I have a constructor:

function Library(author, readingStatus) {
  this.author = author;
  this.readerStatus = readingStatus;
}

And I create objects with it

var One = new Library("One", true);
var Two = new Library("Two", false);

I want to loop over each object, and then within an if/else statement, I want to check if readingStatus is true . If yes, I want to alert something like "already read".

I have tried different ways but it doesn't work. Could anyone show how? EDIT this is what I have tried.

for (var i = 0; i < Library.length; i++) {
var book = "'" + Library[i].title + "'" + ' by ' + Library[i].author + ".";
if (Library[i].readingStatus) {
  window.alert("Already read " + book);
} else
{
 window.alert("You still need to read " + book);
}
}

Library is not an item on which you can iterate. To loop over the objects, it is better to create an array of objects. For example, you've two objects here, One and Two . So you can create an array of them, like this:

var array = [One, Two];

Now you can loop through them and check the desired condition like this:

array.forEach(item => {
  if (item.readerStatus === true) {
    alert('already read');
  }
});

Here is a complete example, in action:

 function Library(author, readingStatus) { this.author = author; this.readerStatus = readingStatus; } var One = new Library("One", true); var Two = new Library("Two", false); var array = [One, Two]; array.forEach(item => { if (item.readerStatus === true) { alert(item.author + ' already read'); } });

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