Cooper Reck Cooper Reck - 19 days ago 7
Javascript Question

How do I create a loop that will actively switch variables?

function calc() {
var a = document.getElementById("yValue").value;
var b = document.getElementById("yValue2").value;
var c = document.getElementById("yValue3").value;
var d = document.getElementById("yValue4").value;
for (i = 0; i < x; i++) {
var x = document.getElementById("amt").value;
var e = Number(a) + Number(b);
var f = Number(b) + Number(c);
var g = Number(c) + Number(d);
var h = Number(d);
document.getElementById("demo").innerHTML = e + ", " + f + ", " + g + ", " + h;
var a = e;
var b = f;
var c = g;
var d = h;
}
}


I am trying to set this up so that the variables e f g h can be moved to a b c d so that the math that is applied can just continue to loop but it is not working, can anyone help me?

Y C Y C
Answer

You haven't initialzied x.

  for (i = 0; i < x; i++) { //x is not defined
    var x = document.getElementById("amt").value;

Should probably be:

var x = document.getElementById("amt").value;
  for (i = 0; i < x; i++) {