-1

I have 9 variables in my javascript code.

s1 = 'n';
s2 = 'n';
s3 = 'n';
s4 = 'n';
s5 = 'n';
s6 = 'n';
s7 = 'n';
s8 = 'n';
s9 = 'n';

I created a function that randomly selects a number from 1-9

function bot() {
   var generateRandomNumber = Math.floor(Math.random() * 9) + 1;
   console.log(generateRandomNumber);
}

How to do it in this function to make it replace the contents of the variable s+generateRandomNumber = 'x'?

E. Ae2
  • 9
  • 3
  • 1
    This sounds like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). I feel like what you're trying to accomplish might have a better way than this specific solution - I'd love to hear a bit more context. – Tyler Roper Jul 16 '18 at 17:26
  • 4
    You're looking for arrays. – SLaks Jul 16 '18 at 17:26
  • 1
    Possible duplicate of [Get global variable dynamically by name string in JavaScript](https://stackoverflow.com/questions/1920867/get-global-variable-dynamically-by-name-string-in-javascript) or [How to get local variable by its name in JS?](https://stackoverflow.com/questions/2146173/how-to-get-local-variable-by-its-name-in-js) or [How can I access local scope dynamically in javascript](https://stackoverflow.com/questions/598878/how-can-i-access-local-scope-dynamically-in-javascript) – Tibrogargan Jul 16 '18 at 17:27
  • array is best solution but if you want to go this way they will be available using window or global object window["s1"] but highly discouraged – sumeet kumar Jul 16 '18 at 17:28
  • Object or array is the way to go. Should be dupes on this.... – epascarello Jul 16 '18 at 17:28

2 Answers2

1

The easiest way I can think of it to put the 9 variables into an object, like so:

var variables = {
    s1: 'n',
    s2: 'n',
    ... and so on
}

Then you can change your bot function to update a variable using the [] syntax:

function bot() {
    var generateRandomNumber = Math.floor(Math.random() * 9) + 1;

    variables['s' + generateRandomNumber] = 'some new value';
}
Richard Walton
  • 4,789
  • 3
  • 38
  • 49
0

I suggest using an Array instead of individual variables:

var s = [];
for(var i=0; i<9;i++) s[i] = 'n';

function bot() {
  var generateRandomNumber = Math.floor(Math.random() * 9); 
  s[generateRandomNumber] = 'tada';
}
geekonaut
  • 5,714
  • 2
  • 28
  • 30