2017-07-03 45 views
3

我目前正在使用Javascript开发一个小游戏,我使用Codacy来查看我的代码并帮我清理它。为什么使用变量调用数组索引不好?

其中最常见的错误是通用对象注入接收器(安全/检测对象注入)。

它发生在我试图访问数组中的值使用变量。就像这个例子:

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

该功能用于在屏幕上显示的项的值的字符串。它接收一个“值”,可以是0,1,2或3,并返回值的字符串。

现在,这里是我的问题:

Codacy告诉我,使用VAR [VAR]应禁止的,因为它会导致安全问题,因为我是相当新的JavaScript的,我想知道为什么,什么是在这种情况下的良好做法。

+0

代码看起来不错。然而,在这里更合适的开关或查找表... –

+0

不,只是一个值的映射:koefficient。和一个班轮...... – Lazyexpert

+2

两个都没有回答OP的问题 - 为什么数组索引查询被报告为不好的安全实践,这是否有效? – shotor

回答

1

通过索引访问有什么不好:该索引可能没有元素。

关于你的代码,我会做一个预置的地图:

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

然后在函数中使用它:

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

您的想法使预设的作品,也是减少代码大小帮助!非常感谢 :) – Nevios