Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to preserve values in a multiple iteration 1

Status
Not open for further replies.

ttomasko

Programmer
Aug 6, 2008
28
Hello,

I have a script that has three levels of for statements. Right now the end result is that I get returned the last values of each array. What I wish however is to preserve the values of the first and second iterations.
Code:
var a = [1,2,3];
var b = ["a","b"];
var c = ["x","y","z"];

for(var i = 0; a.length> i; i++){
	var aValue = a[i];
	for(var j = 0; b.length> j; j++){
		var bValue = b[j];
		for(var k = 0; c.length> k; k++){
			var cValue = c[k];
			}//end for k
		}//end for j
	}//end for i
alert(aValue+bValue+cValue+", ");
This returns 3bz,. However, what I want is:

1ax, 1ay, 1az
1bx, 1by, 1bz
2ax, 2ay, 2az, etc.

How can I construct this to get that result?

Thanks,
Tom
 
Either concatenate the values, or use an array.

Sticking an alert after the loops are finished will always yield only the last results of the loop. Because each time the loop runs, you overwrite the values of your variables.
The Concatenation would look something like:
Code:
var a = [1,2,3];
var b = ["a","b"];
var c = ["x","y","z"];
var finalval="";
for(var i = 0; a.length> i; i++){
    var aValue = a[i];
    for(var j = 0; b.length> j; j++){
        var bValue = b[j];
        for(var k = 0; c.length> k; k++){
            var cValue = c[k];
   [red]    finalval+=aValue + bValue + cValue + ", "; [/red]
            }//end for k
[red]finalval+="\n\r";[/red]
        }//end for j
    }//end for i
alert([red]finalval)[/red];

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Thanks Phil!

Now to stick this in to the much more complicated script...

Tom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top