I am all backwards on some basic loop logic here and can’t seem to figure it out… This is oversimplified, but basically I have an array containing values that evaluate to either true or false. I then want to loop through each array item and if “false”, check the next, etc. until “true” is reached. Once “true” is reached, the loop should end and the function should return “true”, otherwise return “false”.
I think I’m on the right track, but am just missing something crucial… Any help would be greatly appreciated! Thanks!
function functionName() {
var arr = new Array();
arr[0] = false;
arr[1] = true;
arr[2] = false;
for(var i=0; i<arr.length; i++) {
var p = arr[i];
while(p == false) {
return false;
}
}
return true;
}
Very clever. I never thought of using multiple conditions in the for statement! However, I am still running into issues when I add in the rest of the code; i.e., there is some more stuff going on in the script that I tried to keep out for simplicities’ sake. I’ll reiterate and add some more requirements in:
function functionName() {
var arr = new Array();
arr[0] = "name_1";
arr[1] = "name_2";
arr[2] = "name_3";
for(var i=0; i<arr.length; i++) {
var p = FunctionThatReturnsTrueOrFalse(arr[i]);
while(p == false) {
return false;
}
}
return true;
}
Is there a way to do this with a while or do while loop?
function functionName() {
var arr = new Array();
arr[0] = "name_1";
arr[1] = "name_2";
arr[2] = "name_3";
for(var i=0; i<arr.length; i++) {
var p = FunctionThatReturnsTrueOrFalse(arr[i]);
if (p == true) break;
}
return p;
}
I still feel like there is a way to do this with a while loop or something; I’m not sure if the break is “best practices”, although, it works, so I am happy. But just wondering… Any thoughts?