【问题标题】:Javascript Objects, Constructors, only returning final value? [duplicate]Javascript对象,构造函数,只返回最终值? [复制]
【发布时间】:2022-01-03 05:40:12
【问题描述】:

我正在学习对象和构造函数,因此为一本书创建了一个对象。

在对一个元素(书籍或作者或页面或阅读)进行一些测试后,它工作正常,但当我添加超过 1 个时,它只返回最终值。

例如,下面仅在我希望它返回title, author, pages, read 时返回"nope"(正如我认为我的函数"bookInfo" 声明的那样?

我在这里遗漏了什么,因为我已经对照一些示例检查了我的代码并且看不到任何问题?

function Book(title, author, pages, read) {
    this.title = title
    this.author = author
    this.pages = pages
    this.read = read
    this.bookInfo = function() {
        return (title, author, pages, read)
    }

}

const LOTR = new Book('lord of the rings', 'JRR', '366', 'nope');

console.log(LOTR.bookInfo());

// should print 'lord of the rings', 'JRR', '366', 'nope') but only returns 'nope' (or whatever the last value is?)

【问题讨论】:

  • (title, author, pages, read) 不是元组,它是括号中的逗号运算符。你的意思是[title, author, pages, read]
  • @Ry- 请注意,使用直接传递的参数,如果它们中的任何一个被构造函数更改,它将无法正常工作。

标签: javascript


【解决方案1】:

您可以在数组中返回分配的值:

this.bookInfo = function() { 
  return [this.title, this.author, this.pages, this.read]; 
}

或对象:

this.bookInfo = function() { 
  return {title:this.title, author:this.author, pages:this.pages, read:this.read}; 
}

或字符串:

this.bookInfo = function() { 
  return `${this.title} ${this.author} ${this.pages} ${this.read}`; 
}

【讨论】:

    猜你喜欢
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多