Why is this wrong pratice calling array index with variable?

I am currently developing a small game in Javascript and I am using Codacy to view my code and help me clean it up.

One of the most common errors is the generic object injection receiver (security / detect-object-injection).

This happens when I try to access a value in an array using a variable. As in this example:

function getValString(value)
{
    var values = ["Mis&eacuterable", "Acceptable", "Excellente", "Divine"];
    return values[value];
}

      

This function is used to display a string of element values ​​on the screen. It takes a "value", which can be 0, 1, 2, or 3, and returns a string of value.

Now here's my problem:

Codacy tells me that the use of var [var] should be disallowed as it causes security problems and since I'm fairly new to javascript I was wondering why and what are good practices in such a situation.

+3


source to share


1 answer


What's wrong with access by index: there can be no element in this index.

As for 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 a 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);
}

      

+1


source







All Articles