Uncaught typeError: Cannot read property of undefi

2019-08-29 01:21发布

问题:

I don't think my script is identifying an object, and I'm not sure why.

I start with the following data structure:

var state;
var init = function() {
    state = {
        runInfo: { 
            price: null,
            containers: null,
            servings: null
        },
        formula: [],
        totalsServing: [],
        totalsBottle: [],
        totalsRun: []
    };
};

And then add objects to the 'Formula' array:

var addIngredient = function(name, amount, carrier, usdperkilo, origin, packSize) {
        var ingredient = {
            name: name,
            amount: amount,
            carrier: carrier,
            usdperkilo: usdperkilo,
            origin: origin,
            packSize: packSize
        };

        state.formula.push(ingredient);
    };

This all works fine. However, when I create another function to manipulate the objects in the "Formula" array I get an "Uncaught TypeError: Cannot define property 'carrier' of undefined" using this function:

addSection3Row = function(ingredient) {
        var ingredient = state.formula[ingredient].name;
        var carrier = (state.formula[ingredient].carrier/100)*(state.formula[ingredient].amount/(1-(state.formula[ingredient].carrier/100)));
        var amount = state.formula[ingredient].amount;

      var row = {
            ingredient: ingredient,
            carrier: carrier,
            amount: amount,
            totalAmount: carrier + amount
        };

        state.totalsServing.push(row);
    };

I've looked at other questions w/ this error message the issue usually seems to be that javascript hasn't defined the variable yet.

I suspect this is the case for me too, but I can't see why.

I run the following code at the bottom of my page, beneath the html:

init();
addIngredient("St. John's Wort", 500, 4, 25, true, 25);
addIngredient("5-HTP", 100, 2, 165, true, 25);
addSection3Row(0);
console.log(state); 

And when I run the following code in the console:

(state.formula[ingredient].carrier/100)*(state.formula[ingredient].amount/(1-(state.formula[ingredient].carrier/100)))

It returns the correct value. So I know there's something in my script that prohibits js from accessing the object but I'm not sure why.

回答1:

In addSection3Row function you override the ingredient in first row.

addSection3Row = function(ingredient) { //ingredient is number

        var ingredient = state.formula[ingredient].name;//ingredient is string
        var carrier = (state.formula[ingredient].carrier/100)*(state.formula[ingredient].amount/(1-(state.formula[ingredient].carrier/100)));
        var amount = state.formula[ingredient].amount;

      var row = {
            ingredient: ingredient,
            carrier: carrier,
            amount: amount,
            totalAmount: carrier + amount
        };

        state.totalsServing.push(row);
    };