【发布时间】:2020-07-14 16:01:18
【问题描述】:
我试图从我的数组中返回一个对象列表,但我返回的是三个 NAN 值。
var books = [];
function Book(title, author, alreadyRead){
this.title = title
this.author = author
this.alreadyRead = alreadyRead
}
function addBook(title, author, alreadyRead){
var b = new Book(title, author, alreadyRead);
books.push(b);
}
addBook("The Hunger Games", "Suzannee Collins", true);
addBook("The Bible", "Various Authors", true);
addBook("The Hobbit", "J.R.R. Tolkien", false);
function printBooks(books){
let arrayLength = books.length
for(let i = 0; i < arrayLength; i++){
console.log(books.title + books.author);
}
}
printBooks(books);
我不太确定发生了什么,所以谁能帮我解释一下?
【问题讨论】:
-
books.title + books.author- 变量books是 array,因此您尝试获取数组对象的属性title和属性author把它们加在一起。undefined + undefined是NaN。你想要books[i].title + books[i].author -
console.log(books[i].title + books[i].author)— 你有索引变量,你只需要使用它
标签: javascript arrays nan