问题
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érable", "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