为数组[closed]的每个值返回NAN

问题描述 投票:0回答:2

我正在尝试从数组中返回对象列表,但是我返回了三个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);

我不太确定发生了什么,所以有人可以为我阐明一下吗?

javascript arrays nan
2个回答
2
投票

printBooks功能中,您在书本属性上使用for进行迭代,这意味着您必须指定书号,即i->将为book[1].title = "The Hunger Games",依此类推,依此类推

我正在尝试从数组中返回对象列表

在您的职能中,您仅打印它们,这是您想要的吗?

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[i].title + books[i].author);
  }
}


printBooks(books);

0
投票

您缺少for循环中的索引[i]

function printBooks(books){
    let arrayLength = books.length 

    for(let i = 0; i < arrayLength; i++){
        console.log(books[i].title + books[i].author);
    }
 }
© www.soinside.com 2019 - 2024. All rights reserved.