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 John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reverse arrays, what am i doing wrong 1

Status
Not open for further replies.

G00GLER

Instructor
May 17, 2005
57
US

Below is simple html page, when user clicks "test" button should write to layer:
1,2,3,4,5,6,7,8,9
9,8,7,6,5,4,3,2,1

but instead writes
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9

any help much appreciated!

Code:
<HTML>
<BODY>
<SCRIPT>
myArray=new Array([1,2,3,4,5,6,7,8,9]);
s = new Array();  

function writeIt(){
	revIt();
	for (i=0;i<myArray.length;i++){
		//alert(myArray[i]+"<BR>");
		document.getElementById('test').innerHTML+=myArray[i]+"<BR>";
	}
}
function revIt(){
	for (i=0;i<myArray.length;i++){
		//alert(myArray[i]+"<BR>");
		document.getElementById('test').innerHTML+=myArray[i]+"<BR>";
	}
	myArray.reverse();
}
</SCRIPT>
<form>
<input type=button value=test onClick='writeIt();'>
</form>
<div id="test" name="test" style="background-color:black;color:yellow;"></div>
</BODY>
</HTML>
 
Look at the documentation for reverse:
Remarks
The reverse method reverses the elements of an Array object in place. It does not create a new Array object during execution.

If the array is not contiguous, the reverse method creates elements in the array that fill the gaps in the array. Each of these created elements has the value undefined.

Example
The following example illustrates the use of the reverse method.

function ReverseDemo(){
var a, l; //Declare variables.
a = new Array(0,1,2,3,4); //Create an array and populate it.
l = a.reverse(); //Reverse the contents of the array.
return(l); //Return the resulting array.
}
Requirements

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
It IS working, but you only have one element in your array which, reversed, is the same as the original: [1,2,3,4,5,6,7,8,9]. Take the square brackets out of the array declaration and it'll do what you want.

--Dave
 
Good eye, Dave. He has an array with one element, which is an array of the numbers. When he writes it to the screen, it writes the whole array, comma delimited, in the <div>.

Lee
 
good eye indeed, thanks for pointing out obvious, was driving me nuts.
 
The complete <html>-to-</html> code was very helpful in figuring it out. Now THAT's the way to post a question!

:)

'glad I could help out. Thanks for the star!

--Dave
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top