Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-07-2003, 04:31 PM   PM User | #1
adoreae
New to the CF scene

 
Join Date: Jun 2003
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
adoreae is an unknown quantity at this point
Question replacing multiple alert boxes with 1 loop

I need to find out how to replace the five alert boxes with one "for" loop. Here is the code that I have written. Any help would be greatly appreciated.



<strong>Greetings to Friends!</strong> <br />
<SCRIPT LANGUAGE="JavaScript">
/* The following instructions create an array named greetings with five elements and store various greetings in elements 0 to 4 of the array*/
var greetings = new Array (5)
greetings[0] ="Hi"
greetings[1] ="Hello"
greetings[2] ="How are you,"
greetings[3] ="Good to see you,"
greetings[4] ="Have a good day,"
/*The following instructions create an array named names with five elements and store various names in elements 0 to 4 of the array*/

var names = new Array(5)
names [0] = "John"
names [1] = "Jack"
names [2] = "Jenny"
names [3] = "Jill"
names [4] = "Jake"

/*The following instructions write the first greeting and then the first name in an alert box, then the second greeting and the second name in the next alert box, and so on*/
alert(greetings[0] + names[0])
alert(greetings[1] + names[1])
alert(greetings[2] + names[2])
alert(greetings[3] + names[3])
alert(greetings[4] + names[4])
</script>
adoreae is offline   Reply With Quote
Old 07-07-2003, 05:24 PM   PM User | #2
ellisd5
Regular Coder

 
ellisd5's Avatar
 
Join Date: Jun 2002
Location: Uk
Posts: 160
Thanks: 5
Thanked 0 Times in 0 Posts
ellisd5 is an unknown quantity at this point
This is how you do it with a for loop

Code:
    for (i=0; i<names.length; i++) {
        alert(greetings[i] + names[i])
    }
i=0 initises the variable i (spelling rubbish i know)
the i++ increments its value by one which loop.
It does this until i<names.length
names.length is how many itmes are in your array.
ellisd5 is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:30 PM.


Advertisement
Log in to turn off these ads.