如何将字典中使用的代码转换为es5?

q8l4jmvw  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(269)

下面的代码在使用字典的新浏览器中运行良好,如

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的浏览器。
我试着将代码转换成es5https://babeljs.io/repl,但没用。
我怎样才能修好它?

k3bvogb1

k3bvogb11#

在早期版本的js中,阵列上的许多内置属性都是可枚举的。
当你在他们身上绕圈子时 in 您可以获得这些索引以及整数索引。 input['length'] 将是未定义的,就像现在一样 input['push'] .
使用常规的 for (var i = 0; i < index.length; i++)

相关问题