【发布时间】:2021-07-11 19:05:30
【问题描述】:
下面的代码在带有类似字典的新浏览器中运行良好
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,但没有帮助。
我该如何解决?
【问题讨论】:
-
input不是变量。这将在任何 JS 引擎中出错(而不是您引用的错误)。 -
@Quentin 你是想说我不能用
input作为变量名吗?我已经更正了代码以显示我如何定义input。 -
不,我是说你没有定义
input -
var ingredients = CRAFT_DB[6].recipes[0].input.map(function (inp) { return {key: inp[0].index, value: inp[0].count}; }).reduce(function (o, e) { o[inp.key] = o[e.key] || 0 + parseInt(e.value); return o; });
标签: javascript ecmascript-5 es5-compatiblity