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

How to search a loop for only certain elements

Status
Not open for further replies.

ttomasko

Programmer
Aug 6, 2008
28
Hello,

I want to search through an array to make sure all the elements are the same. If so, I want there to be one alert to the user, not as many alerts as there are elements. But if one or more elements do not meet a condition, I want an alert for each of those elements.

Below is the script. In the array here all the elements are "b." I get five alerts when I really only want one. But if I change two of the elements to say "c" and "d", I want just two alerts for those elements. I want to ignore all the "b" elements.

How can I make this work?
Thanks,
Tom

var a = new Array ("b","b","b","b","b");
for(var i = 0; i < a.length; i++){
if(a =="b"){
alert("No problems, everything is b.");
}//end if
else if(a !="b"){
alert("OH oh, you have a "+a+" in the array.");
}//end else if
}//end for
 
var a = new Array ("b","b","b","b","b");
var t = false;
for(var i = 0; i < a.length; i++){
if(a =="b" && t == false){
alert("No problems, everything is b.");
t = true;
}//end if
else if(a =="b" && t == true){
alert("OH oh, you have a "+a+" in the array.");
}//end else if
}//end for
 
Dear kzn,

Your script did not work. I still get multiple alerts in the case that all the elements are "b" and I get multiple alerts in the case that any of the elements are not "b". But what is worse, the "Oh oh" alert returns even when an element is "b".

Tom
 
OK, I found one of the problems. The condition for ELSE IF has to be (a!="b"

So now the script work fine when all elements are the same.

However, when one or more elements are different than "b" I get one alert that says "No problems..." and then an alert for each of the non-"b" elements.

So I need to eliminate that first alert.

Thanks,
Tom
 
This code works:

var a = new Array("b","b","x","c","b");
var flag = '';
for(var i = 0; i< a.length; i++){
if(a=="b" ){
}//end if
else {
if(a!="b" ){
flag = a;
alert("Oh oh, you have a "+flag+" in the array.");}
}//end else if
}//end for
if (flag == '') {
alert("No problem, everything is b.");
}//end if
 
just set a switch to true or false;
after the loop has finished,
if the switch is ture
alert ("switch is true")
else
alert ("switch is false")
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top