简体   繁体   English

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

[英]How to convert the code used with dictionary to ES5?

The code below works well in new browsers with dictionaries like下面的代码在带有字典的新浏览器中运行良好

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);

But I should support ES5.但我应该支持 ES5。 But I get the error TypeError: Cannot read property "index" from undefined with ES5-enabled browser.但是我收到错误TypeError: Cannot read property "index" from undefined with ES5-enabled browser。

I tried to convert the code to ES5 with https://babeljs.io/repl , but it didn't help.我尝试使用https://babeljs.io/repl将代码转换为 ES5,但没有帮助。

How could I fix it?我怎么能修好呢?

In earlier versions of JS a lot of the built-in properties on arrays are enumerable.在早期版本的 JS 中,数组的许多内置属性都是可枚举的。

When you loop over them with in you get those as well as the integer indexes.当你用in循环它们时in你会得到它们以及整数索引。

input['length'] is going to be undefined, as is input['push'] . input['length']将是未定义的, input['push']

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

The following verification helped me -以下验证帮助了我 -

for (var key in input) {
    if (typeof input[key][0] !== 'undefined') {
      ...
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM