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!

Array and String Object

Status
Not open for further replies.

wuzzle

Programmer
Dec 20, 2000
75
CA
How would I write a script that uses an Array, the String Object and a loop to cycle through the strings in the array and find a certain string?
I want it to prompt the user to tell what month they were born in, and then tell them what their zodiac sign is.

questionarray = new Array(13);
questionarray[0] = "January"
questionarray[1] = "February"
questionarray[2] = "March"
questionarray[3] = "April"
questionarray[4] = "May"
questionarray[5] = "June"
questionarray[6] = "July"
questionarray[7] = "August"
questionarray[10] = "September"
questionarray[11] = "October"
questionarray[12] = "November"
questionarray[13] = "December"

var searchstring = prompt("What month were you born in?","Enter your birth month");

...?
 
Well you would do something like:

function getMonth(searchstring){
var month = "invalid month";
for(var j =0; j< questionarray.length;j++){

if( questionarray[j] == searchstring){
// decide what data you want to return

month = j;
}
else{/* do nothing */}
}
return month;
}


Function returns the integer coresspondong to the matching entry in the array.
If no match - the string invalid month is returned.You could add to this and make it pop up an alert or the prompt again.
Perhaps you want to convert what they enter to lowercase, and change your array entries to lowercase, to avoid some errors, when trying for a match - maybe you could use a select box?

b2 - benbiddington@surf4nix.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top