Невозможно прочитать свойство «push» из неопределенного создания свойства массива объекта (Javascript)

1

Мой конструктор Mash должен иметь свойство, являющееся массивом объектов Grain. Это до тех пор, пока я получил, и теперь у меня возникает ошибка с моим нажатием. Какие-нибудь мысли?

 function Grain(maxPPG, quantity) {
        this.maxPPG = maxPPG;
        this.quantity = quantity;


        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);


    function Mash(volume) {
        this.volume = volume;


        this.addGrain = function(grain) {
            this.grains.push(grain);
        }

        this.calcEOG = function() {
            let total = 0;
            this.grains.forEach(item => {
                total += item.calMaxPPG();
            });
            return total / this.volume;

        };
    }

    let mash = new Mash(7);
    mash.addGrain(grain1);
    mash.addGrain(grain2);
    console.log(mash.calcEOG());
  • 0
    Нет объявленной и определенной переменной grains .
Теги:

3 ответа

0
Лучший ответ

Вы забыли инициализировать переменные grains в Mash constructor.

function Mash(volume) {
    this.grains = [];
    this.volume = volume;


    this.addGrain = function(grain) {
        this.grains.push(grain);
    }

    this.calcEOG = function() {
        let total = 0;
        this.grains.forEach(item => {
            total += item.calMaxPPG();
        });
        return total / this.volume;

    };
}

РЕДАКТИРОВАТЬ

Кроме того, ваши экземпляры Grain class не принимают строку в конструкторе. Я не знаю, почему вы начинаете с имени (я думаю).

function Grain(name, maxPPG, quantity) {
    this.name = name;
    this.maxPPG = maxPPG;
    this.quantity = quantity;


    this.calMaxPPG = function() {
        return this.maxPPG * this.quantity;
    };
}

Теперь ваши экземпляры будут работать.

EDIT 2: просто работайте над своим скриптом :)

Ищите эти советы:

// before dealing with data, work on your classes
function Grain(name, maxPPG, quantity) {
    this.name = name;
    this.maxPPG = maxPPG;
    this.quantity = quantity;
}
// and as @HMR said, always declare your class functions with prototypes
Grain.prototype.MaxPPG = function() {
    return this.maxPPG * this.quantity;
};
function Mash(volume, grains) {
    this.volume = volume;
    this.grains = grains;
}
Mash.prototype.calcEOG = function() {
    var total = 0;
    this.grains.forEach(item => {
        total += item.MaxPPG();
    });
    return total / this.volume;
};
// So after all you'll instance your classes easy.
var grain1 = new Grain("Pale Malt (2 Row)", 9, 37),
    grain2 = new Grain("Caramel/Crystal Malt - 20L", .75, 35);
var mash = new Mash(7, [grain1, grain2]); // note that litle change I did :p
console.log(mash.calcEOG());
  • 0
    Спасибо! это прояснило проблему, но теперь я получаю NaN: /
  • 0
    @CameronGray, посмотри на меня, хе-хе. Оба занятия с небольшими ошибками
Показать ещё 2 комментария
0

вы не объявили массив для ввода

  • 0
    Плюс Grain конструктор вызывается с 3 параметрами, но определяется с 2 параметрами.
0

У вас есть несколько ошибок, конструктор вызывается с 3 параметрами, но вы определяете его только с 2. Вы не инициализировали массив графов.

Один совет: поведение может идти по прототипу.

Исправленный код будет выглядеть так:

function Grain(name,maxPPG, quantity) {//constructor takes 3 parameters when you call it
  this.name = name;//assume the first one is name
  this.maxPPG = maxPPG;
  this.quantity = quantity;
}
//you an add behavior on the prototype:
Grain.prototype.calMaxPPG = function() {
  return this.maxPPG * this.quantity;
};

let grain1 = new Grain("Name of grain", 9, 37);
let grain2 = new Grain("Name of grain", .75, 35);


function Mash(volume) {
  this.volume = volume;
  this.grains=[];//you did not initialize grains
}
//again; add behavior on the prototype
Mash.prototype.addGrain = function(grain) {
  this.grains.push(grain);
};
Mash.prototype.calcEOG = function() {
  //using reduce instead to sum up all grains
  return this.grains.reduce(
    function(all,item){
      return all + item.calMaxPPG();
    },
    0
  )/this.volume;
};
let mash = new Mash(7);
mash.addGrain(grain1);
mash.addGrain(grain2);
console.log(mash.calcEOG());

Ещё вопросы

Сообщество Overcoder
Наверх
Меню