0

下面的代码在带有字典的新浏览器中运行良好

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但是我在启用 ES5 的浏览器中遇到了错误。

我尝试使用https://babeljs.io/repl将代码转换为 ES5 ,但没有帮助。

我该如何解决?

4

2 回答 2

1

在早期版本的 JS 中,数组的很多内置属性都是可枚举的。

当您遍历它们时,in您会得到这些以及整数索引。

input['length']将是未定义的,就像input['push'].

使用常规for (var i = 0; i < index.length; i++)循环。

于 2021-07-11T19:16:21.690 回答
0

以下验证帮助了我 -

for (var key in input) {
    if (typeof input[key][0] !== 'undefined') {
      ...
    }
 }
于 2021-07-15T19:45:50.113 回答