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

落花浮王杯 提交于 2019-11-27 07:06:23

问题


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 Object Injection Sink (security/detect-object-injection).

It happens when i'm trying to access a value in an array using a variable. Like in this example :

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

This function is used to display on screen the value's string of an item. It receives a "value" which can be 0, 1, 2 or 3 and returns the string of the value.

Now here's my problem :

Codacy is telling me that use of var[var] should be prohibited because it causes security issues and since i'm rather new to javascript, i was wondering why and what are the good practices in that kind of situation.


回答1:


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);
}


来源:https://stackoverflow.com/questions/44882542/why-is-it-bad-pratice-calling-an-array-index-with-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!