start true, stay false

If you have the need to set a Boolean to be true only if every condition is met but false if it fails just once then try this:

var test:Array = [true, true, true, false, false, true, false, true];
var isAllTrue:Boolean = true;
for(var i:Number = 0; i < test.length; ++i) {

isAllTrue = ( test[i] && isAllTrue ) ? true : false;
trace(i + ” : ” + isAllTrue);

}

Output:
0 : true
1 : true
2 : true
3 : false
4 : false
5 : false
6 : false
7 : false

Notice that part of the trinary condition is isAllTrue. That way if isAllTrue ever switches to false the condition will be false thereafter.

This instance isn’t a great example because in this case you would probably want to break out of the loop as soon as your condition was false. There’s no need to keep going through the loop.

If you find a more appropriate use for this snippit let me know.

Tags: