简体   繁体   中英

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. But I get the error 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.

How could I fix it?

In earlier versions of JS a lot of the built-in properties on arrays are enumerable.

When you loop over them with in you get those as well as the integer indexes.

input['length'] is going to be undefined, as is input['push'] .

Use a regular for (var i = 0; i < index.length; i++) loop.

The following verification helped me -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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