[英]Function doesn't see Object property, but console.log does
I'm making a book library.我正在做一个图书馆。
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;
}
}
Now I made a function that will generate a Book object and will take user inputs as property values:现在我创建了一个函数,它将生成一个 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));
}
I make a function that will loop through the myLibrary array and sort them based on property values.我创建了一个函数,它将遍历myLibrary数组并根据属性值对它们进行排序。 For example:
例如:
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);
}
}
}
Now I will load my page and add an object using addBookToLibrary function.现在我将加载我的页面并使用 addBookToLibrary 函数添加一个对象。 Now myLibrary[0].onPage returns a number that was taken from the input by addBookToLibrary.
现在 myLibrary[0].onPage 返回一个由 addBookToLibrary 从输入中获取的数字。 So why does function showBooks fail?
那么为什么函数 showBooks 会失败呢? It says it can not read onPage property of undefined.
它说它无法读取未定义的 onPage 属性。
As @ASDFGerte stated, your loop is wrong.正如@ASDFGerte 所说,你的循环是错误的。 If you use <=, you will run into the issue that the last entry will not exist.
如果使用 <=,则会遇到最后一个条目不存在的问题。
your array for examples has length 5, meaning the index from 0 to 4 is filled.您的示例数组的长度为 5,这意味着填充了 0 到 4 的索引。 If you start with i = 0, then the last index you try to adress will be 5 (array.length = 5).
如果您从 i = 0 开始,那么您尝试寻址的最后一个索引将为 5 (array.length = 5)。 So if you want to use <=, you need to stop at array.length - 1.
所以如果你想使用<=,你需要在array.length - 1处停止。
Or, like @ASDFGerte stated, just use < and the loop will stop at the last filled entry, because 4 < 5.或者,就像@ASDFGerte 所说的那样,只需使用 < 循环将在最后一个填充的条目处停止,因为 4 < 5。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.