2017-07-03 70 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