Is it possible to call a variable by concatenating two strings in JavaScript? -
i'm trying condense code , i've looked @ number of articles on concatenating variables haven't been able work way need to.
below 2 snippets of code. functionally identical except first snippet has variables use 'str' in name , second snippet uses 'dex' instead. plan on creating similar code 'int' , 'ht' don't want copy / paste , go change 'str, dex, int, ht' names on code on , on again.
is possible put 'str, dex, int, ht' variable [var1] (according button pressed) , use [var1] in place of 'str, dex, int, ht' code has written once?
//define stength increase function var strincrease = function () { //increase playerstrength 1 playerstr = playerstr + 1; playerstrdisplay.innerhtml = playerstr; //increase strengthcp 10 strcp = strcp + strcost; strcpdisplay.innerhtml = strcp; //decrease totalcp 10 totalcp = totalcp - strcost; totalcpdisplay.innerhtml = totalcp; } //define dexterity increase function var dexincrease = function () { //increase playerdexterity 1 playerdex = playerdex + 1; playerdexdisplay.innerhtml = playerdex; //increase dexteritycp 20 dexcp = dexcp + dexcost; dexcpdisplay.innerhtml = dexcp; //decrease totalcp 20 totalcp = totalcp - dexcost; totalcpdisplay.innerhtml = totalcp; }
you define attributes properties of objects , access them using strings, this:
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); } . . .
Comments
Post a Comment