是否可以通过在JavaScript中连接两个字符串来调用变量?

时间:2015-05-31 19:43:31

标签: javascript variables concatenation

我正在尝试压缩我的代码,我已经查看了一些关于连接变量的文章,但是我无法按照我需要的方式工作。

以下是两段代码。它们在功能上是相同的,除了第一个片段的变量在其名称中使用'Str'而第二个片段使用'Dex'代替。我计划使用'Int'和'Ht'创建类似的代码,但我不想复制/粘贴,然后回过头来反复更改我的代码中的'Str,Dex,Int,Ht'名称。

是否可以将'Str,Dex,Int,Ht'放入变量[var1](根据按下的按钮)然后使用[var1]代替'Str,Dex,Int,Ht'所以代码只需要写一次?

//Define Stength Increase Function
var strIncrease = function () {
//Increase playerStrength by 1
    playerStr = playerStr + 1;
    playerStrDisplay.innerHTML = playerStr;
//Increase strengthCP by 10
    strCP = strCP + strCost;
    strCPDisplay.innerHTML = strCP;
//Decrease totalCP by 10
    totalCP = totalCP - strCost;
    totalCPDisplay.innerHTML = totalCP;
}

//Define Dexterity Increase Function
var dexIncrease = function () {
//Increase playerDexterity by 1
    playerDex = playerDex + 1;
    playerDexDisplay.innerHTML = playerDex;
//Increase DexterityCP by 20
    dexCP = dexCP + dexCost;
    dexCPDisplay.innerHTML = dexCP;
//Decrease totalCP by 20
    totalCP = totalCP - dexCost;
    totalCPDisplay.innerHTML = totalCP;
}

3 个答案:

答案 0 :(得分:4)

您可以将对象用作地图:

var player = { str: 0, dex: 0, ... };

function increase(stat) {
    player[stat]++;
    document.getElementById(stat + 'Display').innerHTML = player[stat];
}

increate('str');

答案 1 :(得分:0)

您可以将属性定义为对象的属性,并使用字符串访问它们,如下所示:

var player = {
    str: 1,
    dex: 1,
    in: 1,
    ht: 1,
    strCP: 10,
    dexCP: 10,
    intCP: 10,
    htCP: 10,
    totalCP: 0
},
costs = {
   strCost: 10,
   dexCost: 10,
   inCost: 10,
   htCost: 10
};

function increaseAttribute(player, costs, attr) {
    player[attr] += 1;
    player[attr + "CP"] += costs[attr + "Cost"];
    player.totalCP += costs[attr + "Cost"];
.
.
}

function increaseStr () {
   increaseAttribute(player, costs, attr);
}
.
.
.

答案 2 :(得分:-1)

您可以使用closure动态生成方法。

例如。

var player = { 
   str : 0
   dex : 0
   int : 0
   ht : 0
}

function methodFactory (player, property, diff) {
    var mathod = function () {
        player[property] += diff;
    }
    return method;
}

然后

var addInt = methodFactory (player, 'int', 1);
var addIntBy2 = methodFactory (player, 'int', 2);

addInt();

写一次,到处使用