簡體   English   中英

如何將字典使用的代碼轉換為 ES5?

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

下面的代碼在帶有字典的新瀏覽器中運行良好

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 with ES5-enabled browser。

我嘗試使用https://babeljs.io/repl將代碼轉換為 ES5,但沒有幫助。

我怎么能修好呢?

在早期版本的 JS 中,數組的許多內置屬性都是可枚舉的。

當你用in循環它們時in你會得到它們以及整數索引。

input['length']將是未定義的, input['push']

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

以下驗證幫助了我 -

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