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

JavaScript中创建对象数组属性时出现push未定义错误求助

解决Mash对象push Grain报错的问题

我来帮你排查代码里的关键问题,一步步解决push操作的报错:

1. 先修正Grain构造函数与实例化的不匹配问题

你定义的Grain构造函数只接收maxPPG和quantity两个参数,但实例化时传了三个值(谷物名称、数量、maxPPG),而且构造函数里没有存储名称的属性,这会导致实例的属性值完全错位,后续操作肯定出问题。

修正后的Grain构造函数与实例化代码:

function Grain(name, quantity, maxPPG) { 
  this.name = name; // 新增谷物名称属性
  this.quantity = quantity; 
  this.maxPPG = maxPPG; 
  this.calMaxPPG = function() { 
    return this.maxPPG * this.quantity; 
  }; 
}

// 现在参数顺序和构造函数对应,实例属性正确
let grain1 = new Grain("Pale Malt (2 Row)", 9, 37); 
let grain2 = new Grain("Caramel/Crystal Malt - 20L", .75, 35); 

2. 给Mash构造函数添加存储Grain的数组并完善addGrain方法

你的Mash构造函数里没有初始化用于存储Grain对象的数组属性,而且addGrain方法的function拼写错误(写成了functio...),这是导致push报错的核心原因——根本找不到要push的数组。

修正后的Mash构造函数:

function Mash(volume) { 
  this.volume = volume; 
  this.grains = []; // 初始化空数组,专门用来存储Grain实例
  this.addGrain = function(grain) {
    // 可选:添加类型校验,确保只能加入Grain对象
    if (grain instanceof Grain) {
      this.grains.push(grain);
    } else {
      console.error("只能添加Grain类型的对象哦");
    }
  };
}

3. 测试正常调用的示例

现在你可以顺利添加Grain对象了:

// 创建Mash实例
let myBrewMash = new Mash(5);
// 添加谷物
myBrewMash.addGrain(grain1);
myBrewMash.addGrain(grain2);

// 查看存储的谷物数组
console.log(myBrewMash.grains);
// 计算总PPG
let totalPPG = myBrewMash.grains.reduce((total, grain) => total + grain.calMaxPPG(), 0);
console.log("总PPG值:", totalPPG);

额外优化小建议

  • 把Grain的calMaxPPG方法放到原型上,避免每个实例都生成重复的函数:
Grain.prototype.calMaxPPG = function() {
  return this.maxPPG * this.quantity;
};
  • 给Mash添加计算总PPG的方法,方便后续复用:
Mash.prototype.getTotalPPG = function() {
  return this.grains.reduce((total, grain) => total + grain.calMaxPPG(), 0);
};
// 调用方式:myBrewMash.getTotalPPG()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:59:56