Uncaught typeError: Cannot read property of undefined - object

Uncaught typeError: Cannot read property of undefined - object

我认为我的脚本没有识别对象,我也不确定为什么。

我从以下数据结构开始:

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

然后添加对象到'Formula'数组:

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

一切正常。但是,当我创建另一个函数来操作 "Formula" 数组中的对象时,我使用此函数得到一个 "Uncaught TypeError: Cannot define property 'carrier' of undefined":

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

我查看了带有此错误消息的其他问题,问题通常似乎是 javascript 尚未定义变量。

我怀疑我也是这种情况,但我不明白为什么。

我 运行 在页面底部 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); 

当我 运行 在控制台中输入以下代码时:

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

它 returns 正确的值。所以我知道我的脚本中有一些东西禁止 js 访问对象,但我不确定为什么。

在 addSection3Row 函数中,您覆盖了第一行中的成分。

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