为什么用变量调用数组索引是不好的做法? [英] Why is it bad pratice calling an array index with a variable?

查看:524
本文介绍了为什么用变量调用数组索引是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Javascript开发一款小游戏,我正在使用 Codacy 来审核我的代码和帮我清理它。

I'm currently developing a little game in Javascript and i'm using Codacy to review my code and help me cleaning it.

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

当我尝试使用变量访问数组中的值时会发生这种情况。就像在这个例子中一样:

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

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

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.

现在这是我的问题:

Codacy告诉我应该禁止使用var [var],因为它会导致安全问题,因为我对javascript很新,我想知道为什么以及有什么好的做法那种情况。

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.

推荐答案

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

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

然后在功能中使用它:

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

这篇关于为什么用变量调用数组索引是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆