我不认为我的脚本正在识别一个对象,我不确定为什么。
我从以下数据结构开始:
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:无法使用此函数定义未定义的属性'载体':
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);
};
我已经查看了其他问题w /此错误消息问题通常似乎是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访问该对象,但我不确定原因。
答案 0 :(得分:1)
在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);
};