Click to See Complete Forum and Search --> : if Array ==


bt-nd
03-23-2003, 10:00 PM
In JS 1.2 & beyond an array can be defined as:

direction = [0,0,0,0,0,0,0,0,0] which assigns zero to direction[0] thru direction[8]. I needed to test for the array values and tried:

if (direction == [0,0,0,0,0,0,0,0,0]) , but it doesn't work. I was able to get what I need by using:
if (direction[0] == 0 && direction[1] == 0 && direction[2] == 0 && direction[3] == 0 && direction[4] == 0 && direction[5] == 0 && direction[6] == 0 && direction[7] == 0 && direction[8] == 0)

Now can anyone shed some light on why the first if statement doesn't work? It seems to be equivilant to the workable version.

thanks in advance, BT

rkmarcks
03-23-2003, 10:21 PM
The square brackets are actually an array operator. As such, your example probably failed simply because of a missapplication of the brackets.

You didn't say if you were trying to check to see if the elements of your array were equal to zero, or if they were equal to some dynamic array of values.

If the former, then create a dummy array filled with zeroes. Do not perform any matrix operations on that array, use it only to compare to your original array. If all of the values you are comparing are the same, you could also use a for-next loop to make the comparison.

If you want to compare your array to some dynamic array of values, that is probably more difficult, but would likely dpend on how your data is input in the first place.

rkm

AdamBrill
03-23-2003, 10:33 PM
This will check if all the elements in an array are 0:for(x=0; x<arrayName.length; x++){
if(arrayName[x]!=0){
//runs this if one of the elements aren't 0
break;
}
}I hope that helps... ;)

Nedals
03-23-2003, 11:03 PM
re: rkmarcks' comment; this works
direction = (0,0,0,0,0,0,0,0,0);
if (direction == (0,0,0,0,0,0,0,0,0))

bt-nd
03-24-2003, 08:48 AM
Thanks for the great help. The for loop described by rkmarcks and defined by AdamBrill work great, I hope that as I get more comfortable with JS, that I start seeing more of these solutions myself.

I tested the solutionn by nedals and it works as far as a conditional, but the first statement

direction=(0,0,0,0,0,0,0,0,0)

doesn't difine an array, so it doesn't seem to do what I need. The following short debugging script show the solution and the problem with the one that didn't work.

thanks again, BT



<html>
<head>
<title>empty</title>
</head>
<body>
<script LANGUAGE="Javascript" type="text/javascript">
direction = (0,0,0,0);
if (direction == (0,0,0,0)) {
alert("It works, but it also says that direction[1] = " + direction[1]);
}
else {
alert("It doesn't work");
}

set3 = [0,0,7,0]
for(x=0; x<set3.length; x++){
if(set3[x]!=0){
//runs this if one of the elements aren't 0
alert("set3[" + x + "]" + " isn't zero");
}
}
</script>
</body>
</html>