【问题标题】:Returning NAN for each value of array [closed]为数组的每个值返回 NAN [关闭]
【发布时间】: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 - 变量 booksarray,因此您尝试获取数组对象的属性 title 和属性 author把它们加在一起。 undefined + undefinedNaN。你想要books[i].title + books[i].author
  • console.log(books[i].title + books[i].author) — 你有索引变量,你只需要使用它

标签: javascript arrays nan


【解决方案1】:

你在 for 循环中缺少索引 [i]

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

    for(let i = 0; i < arrayLength; i++){
        console.log(books[i].title + books[i].author);
    }
 }

【讨论】:

    【解决方案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);

    【讨论】:

      猜你喜欢
      • 2012-01-01
      • 2020-08-03
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      相关资源
      最近更新 更多