Reputation: 495
I seem to be lost or just seem to be confused. To simplify the problem: I want to check whether each in an array holds true and if and only if all are true it should return a specific value.
var trueArray=[true,true,true,true];
As in my code, the array can have length up to 100 elements, I can't simply check for every element but need a for loop.
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===true)
{
//do something
}
}
However, the above code does something on each step of the loop but I only want it to do something once every condition held true and not in between. Can't think of the solution at the moment?
Upvotes: 0
Views: 94
Reputation: 18022
If it's guaranteed to be a boolean
you can check if any of them are false instead of if they're all true with Array.prototype.indexOf
if(trueArray.indexOf(false) === -1) {
// none are false, so do stuff
}
You wouldn't need to use a loop or create a function.
Upvotes: 2
Reputation: 338
You can do it like this...
var trueArray=[true, true, true, true];
var allTrue=false;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
allTrue=false;
break;
}
else
{
allTrue=true;
}
}
if(allTrue==true)
{
// do something if all values are true
}
You must break the loop if the false value is detected.
Upvotes: 0
Reputation: 1075
You should short circuit the logic as soon as you get a false value, must answers are not getting your question because of the misleading logic you put inside the for even though you only want it done once if all values are true.
You need something like
var flag=true; for(var i =0;i
if (flag) { do something}
Upvotes: 0
Reputation: 780798
if (trueArray.every(function(x) { return x; })) {
//do something
}
Upvotes: 2
Reputation: 24901
Try the following code:
var currentValue = true;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
currentValue = false;
}
}
if(currentValue === true){
//do something
}
Upvotes: 0
Reputation: 2810
Declare a check variable who is already true and set it to false if one of your array values is false. After that, check if it's true and do something.
Example:
var trueArray=[true,true,true,true];
var bCheckArrayVal = true;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
bCheckArrayVal = false;
}
if (bCheckArrayVal) {
// do something if true
} else {
// do something if false
}
}
Upvotes: 0