1

I am currently trying to make Solitare for a school project and have run into an issue of trying to make a counter for the suit piles. The way I am currently trying to do this is by defining a global variable like is shown below:

var Hpilecount = "01";
var Dpilecount = "01";
var Spilecount = "01";
var Cpilecount = "01";

and I am trying to refer to this variable as is shown below:

function movecard(id) {
    console.log(id[0]+pilecount);
}

How can I combine the element of the varible id and something to refer to these variables.

Thanks for the help

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
G.Ward
  • 51
  • 5
  • Possible duplicate of [Use dynamic variable names in JavaScript](https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) – ibrahim mahrir Oct 22 '17 at 12:41

1 Answers1

1

If they are in the global scope, then you can use window with bracket notation to access them (as all golbal variables are properties in the global object window):

var Hpilecount = "01";
var Dpilecount = "01";
var Spilecount = "01";
var Cpilecount = "01";

var id = "C";
var value = window[id + "pilecount"];

console.log(value);

If not then just group them into an object and use that oject to access the value:

var pack = {
  Hpilecount: "01",
  Dpilecount: "01",
  Spilecount: "01",
  Cpilecount: "01"
}

var id = "C";
var value = pack[id + "pilecount"]; // use pack instead of window

console.log(value);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73