问题描述
下面的代码在带有字典的新浏览器中运行良好
var CRAFT_DB = {
6: {
id: "6",type: "blockC",name: "local name",recipes: [{
type: "new",count: "2",input: [
[{
index: "4",count: "1"
}],[{
index: "21",count: "1"
}]
]
}]
}
}
var input = CRAFT_DB[6].recipes[0].input;
var ingredients = {};
for (var key in input)
ingredients[input[key][0].index] = void 0 === ingredients[input[key][0].index] ? parseInt(input[key][0].count) : ingredients[input[key][0].index] + parseInt(input[key][0].count);
但我应该支持 ES5。但是我在启用 ES5 的浏览器中收到错误 TypeError: Cannot read property "index" from undefined
。
我尝试使用 https://babeljs.io/repl 将代码转换为 ES5,但没有帮助。
我该如何解决?
解决方法
在早期版本的 JS 中,数组的许多内置属性都是可枚举的。
当你用 in
遍历它们时,你会得到它们以及整数索引。
input['length']
将是未定义的,input['push']
也是如此。
使用常规的 for (var i = 0; i < index.length; i++)
循环。
以下验证对我有帮助 -
for (var key in input) {
if (typeof input[key][0] !== 'undefined') {
...
}
}