函数看不到对象 属性,但 console.log 可以

Function doesn't see Object property, but console.log does

我正在制作图书馆。

let myLibrary = []; //to store my Book Objects

function Book(title, author, onPage, totalPages) { //constructor function
  this.title = title;
  this.author = author;
  this.onPage = onPage;
  this.totalPages = totalPages;
  this.info = function() {
    return this;
  }
}

现在我创建了一个函数,它将生成 Book 对象并将用户输入作为 属性 值:

function addBookToLibrary() {
  let a = document.getElementById('bookTitle').value;
  let b = document.getElementById('authorName').value;
  let c = document.getElementById('onPage').value;
  let d = document.getElementById('numOfPages').value;
  myLibrary.push(new Book(a, b, c, d));
}

我创建了一个函数,它将遍历 myLibrary 数组并根据 属性 值对它们进行排序。例如:

function showBooks() {
  for (i = 0; i <= myLibrary.length; i++) {
    if (Number(myLibrary[i].onPage) < Number(myLibrary[i].totalPages)
      let newLi = document.createElement('li');
      newLi.innterText = myLibrary[i].title + ' by ' + myLibrary[i].author;
      inProgressBooks.prepend(newLi);
    }
  }
}

现在我将加载我的页面并使用 addBookToLibrary 函数添加一个对象。现在 myLibrary[0].onPage returns 一个由 addBookToLibrary 从输入中获取的数字。那么为什么函数 showBooks 会失败呢?它说它无法读取 onPage 属性 of undefined.

正如@ASDFGerte 所说,您的循环是错误的。如果你使用<=,你将运行陷入最后一个条目不存在的问题。

例如,您的数组长度为 5,这意味着从 0 到 4 的索引已填充。如果您从 i = 0 开始,那么您尝试寻址的最后一个索引将为 5 (array.length = 5)。所以如果要使用<=,需要停在array.length - 1.

或者,就像@ASDFGerte 所说的那样,只需使用 < 并且循环将在最后一个填充的条目处停止,因为 4 < 5.