You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript构造函数返回多属性时仅输出最后一个值是什么原因?

问题原因

你的代码中return (title, author, pages, read)使用了JavaScript的逗号运算符,该运算符的规则是依次计算括号内的所有表达式,最终仅返回最后一个表达式的结果,所以你最终只会拿到最后一个参数read的值"nope"。

另外建议你在构造函数的方法内通过this访问实例属性,而非直接读取构造函数的参数:如果后续你修改了实例的属性值,构造函数的入参值是不会同步更新的,用this才能获取到实例的最新属性。

修复方案

根据你想要的返回格式选择对应写法即可:

  • 若要返回包含所有属性的数组:将返回语句的括号替换为数组方括号
    return [this.title, this.author, this.pages, this.read]
    
    调用console.log输出结果为:['lord of the rings', 'JRR', '366', 'nope']
  • 若要返回你预期的逗号分隔字符串:使用模板字符串拼接属性
    return `${this.title}, ${this.author}, ${this.pages}, ${this.read}`
    
    调用console.log输出结果为:lord of the rings, JRR, 366, nope
  • 若要返回包含所有属性的对象:写成对象字面量格式
    return { title: this.title, author: this.author, pages: this.pages, read: this.read }
    

完整修正示例

function Book(title, author, pages, read) {
    this.title = title
    this.author = author
    this.pages = pages
    this.read = read
    this.bookInfo = function() {
        // 此处可根据需求替换为上面的任意返回写法
        return [this.title, this.author, this.pages, this.read]
    }
}

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

内容的提问来源于stack exchange,提问作者nc14

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:15:04