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

Array elements in an array

Status
Not open for further replies.

jiknik

Technical User
Joined
Jun 11, 2006
Messages
1
Location
AU
I have an array and i want something to happen if any two elements of the array are equal: why is this not working

var jodoo=new Array(9)
for (i=1; i<9; i++){
jodoo=Math.round((Math.random()*300)-1);
}

if (((jodoo)==(jodoo))){
parent.frame0.document.images[jodoo].src="Images/explosion.jpg";

return;
}
 
Because you are doing the comparison outside of the loop, you are always comparing the last element with itself, so it would always match. You would really need two loops.

Also note that array indeces start at 0, not 1, so your array above ony has 8 items in it, not 9.

Try this:

Code:
// Define the array
var arrayLength = 9;
var jodoo = new Array(arrayLength);

// Populate the array
for (var loop=0; loop<arrayLength; loop++) jodoo[loop] = Math.round((Math.random() * 300) - 1);

// Check for duplicate entries
for (var loop1=0; loop1<(arrayLength-1); loop1++) {
	for (var loop2=(loop1+1); loop2<arrayLength; loop2++) {
		if (jodoo[loop1] == jodoo[loop2]) {
			parent.frame0.document.images[jodoo[loop1]].src = 'Images/explosion.jpg';
			return;
		}
	}
}

I start the inner loop after the outer loop, otherwise you'll only be checking elements twice unnecessarily.

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top