【问题标题】:How to convert the code used with dictionary to ES5?如何将字典使用的代码转换为 ES5?
【发布时间】: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


【解决方案1】:

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

当你用in 循环它们时,你会得到它们以及整数索引。

input['length'] 将是未定义的,input['push'] 也是如此。

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

【讨论】:

    【解决方案2】:

    以下验证对我有帮助 -

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

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 2017-11-08
      • 2021-12-18
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多