[英]How to convert the code used with dictionary to ES5?
下面的代码在带有字典的新浏览器中运行良好
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。 但是我收到错误TypeError: Cannot read property "index" from undefined
with ES5-enabled browser。
我尝试使用https://babeljs.io/repl将代码转换为 ES5,但没有帮助。
我怎么能修好呢?
在早期版本的 JS 中,数组的许多内置属性都是可枚举的。
当你用in
循环它们时in
你会得到它们以及整数索引。
input['length']
将是未定义的, input['push']
。
使用常规for (var i = 0; i < index.length; i++)
循环。
以下验证帮助了我 -
for (var key in input) {
if (typeof input[key][0] !== 'undefined') {
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.