循环对象构造函数

问题描述 投票:1回答:1

我有一个构造函数:

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

我用它创建对象

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

我想循环遍历每个对象,然后在if / else语句中,我想检查readingStatus是否是true。如果是,我想提醒“已经阅读”之类的内容。

我尝试了不同的方法,但它不起作用。谁能说明怎么样?编辑这是我尝试过的。

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);
}
}
javascript loops if-statement javascript-objects
1个回答
1
投票

Library不是您可以迭代的项目。要遍历对象,最好创建一个对象数组。例如,你在这里有两个对象,OneTwo。所以你可以创建一个数组,如下所示:

var array = [One, Two];

现在你可以遍历它们并检查所需的条件,如下所示:

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

这是一个完整的示例,在行动中:

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');
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.