0

I am new to Javascript and therefore have a simple question. I am trying to programme a for loop within which new variables can be created using the i value. How can I refer to i to change the variable names (without using an array)? In the example below I want to create top1, top2, left1, left2 etc.

        var i;

        for (i=1; i<3; i++) {

            var top'i'=Math.random(); top'i'=450*top-150;

            var left'i'=Math.random(); left'i'=left*1150;

            document.getElementById("image'i'").style.top=top'i'+"px";

            document.getElementById("image'i'").style.left=left'i'+"px";

            document.getElementById("image'i'").style.display="block";

        }
Amit
  • 1
  • 2
  • 1
    you don't need "new variables", those temporary variables are fine. as for the id, you have to change that, but that's not a variable... i guess you want concatenation – Karoly Horvath Nov 22 '14 at 17:12
  • thanks! very helpful and great programming tip. – Amit Nov 22 '14 at 18:05

1 Answers1

2

You can use

for (var i=1; i<3; i++) {
    var top = Math.random()*450 - 150,
        left = Math.random()*1150,
        el = document.getElementById("image" + i);
    el.style.top = top + "px";
    el.style.left = left + "px";
    el.style.display="block";
}

Simply, at each iteration you will override the values of the previous iteration.

Oriol
  • 274,082
  • 63
  • 437
  • 513