1

I'm trying to use a for loop to give values to three vars (but it could be 2 or even 100 vars, that's not the problem, I guess), and I want to use the value of i to indicate a var name with the name "num1" for example making the code look like num[i] = x or num + [i] = x (I tried both but none worked). I'm not sure what I am doing wrong. Here's my code so far:

function numbers() {
  var num1, num2, num3 = 0;

  for (var i = 1; i < 4; i++) {
    num[i] = Math.floor(Math.random() * 999);
    document.getElementById("n1").innerHTML = num[i];
  }
}

I also want to make the document.getElementById("n1").innerHTML get the number in "n[number]" from the I value, something like "n" + [i], but it doesn't work neither.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

1 Answers1

1

You could use window['name'] like :

 function numbers() {
   var num1, num2, num3 = 0;

   for (var i = 1; i < 4; i++) {
     window['num'+i] = Math.floor(Math.random() * 999);
     document.getElementById("n1").innerHTML = window['num'+i];
   }
 }

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • That won't work. The variables are locally scoped to the `numbers` function. They are not global and thus not available as properties of the `window` object. – Quentin Nov 15 '17 at 18:07
  • 1
    @Quentin He's copying the local variables value to properties on `window` - There's no need to access `num1, num2` after that assignment – nicholaswmin Nov 15 '17 at 18:09
  • 1
    Yes! As for now, it worked as intended. The only problem is that I can't use window[] in the getElementByID. It doesn't work, but well, as for everything else, it worked like a charm! – Javier Green Nov 15 '17 at 18:31