Why is it bad pratice calling an array index with a variable?

后端 未结 3 1817
灰色年华
灰色年华 2020-12-11 03:17

I\'m currently developing a little game in Javascript and I\'m using Codacy to review my code and help me cleaning it.

One of the most seen error is Generic O

3条回答
  •  执念已碎
    2020-12-11 03:30

    What is bad in accessing by index: there might be no element at that index.

    Regarding your code, I would make a preset map:

    const preset = {
      0: 0.5,
      1: 1.5,
      2: 2,
      3: 3
    };
    

    And then use it in function:

    function sellPotato(x, player) {
      // This additional check gives you more confidence in accessing element of and array by index
      if (player.inventory.length < x) return;
    
      if (preset[player.inventory[x].value]) {
        player.money += player.inventory[x].price * preset[player.inventory[x].value];
      }
      player.inventory.splice(x, 1);
      display(player);
    }
    

提交回复
热议问题