未捕获的类型错误: 无法读取未定义的 - 对象的属性

Uncaught typeError: Cannot read property of undefined - object

本文关键字:未定义 读取 对象 属性 类型 错误      更新时间:2023-09-26

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

我从以下数据结构开始:

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

然后将对象添加到"公式"数组中:

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"数组中的对象时,使用此函数得到"未捕获的类型错误:无法定义未定义的属性'carrier'":

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

它返回正确的值。 所以我知道我的脚本中有一些东西禁止 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);
    };