js: loops and selection, arrays and random jbwyatt.com

Tryit Editor


1. LOOP and show (alert) the five numbers , 0-4 using "for" <script type="text/javascript"> var i; for( i=0; i<5; i++) { alert(i); } </script>


2. LOOP with IF using "while" and "do while" <script type="text/javascript"> //LOOP through the numbers 0-9, showing (alert) IF even #s using "while" var i=0; while( i < 10) { if(i % 2 === 0) alert(i); i++; } // LOOP through the numbers 1-10, showing IF odd #s using "do while" var i=1; do{ if(i % 2 === 1) alert(i); i++; }while( i <= 10); </script>


3. ARRAY <script type="text/javascript"> var i; // declare an array called billy with 5 items // index of items is 0 thru 4 var billy = new Array(5); // fill array with numbers 0, 2, 4, 6, 8 for(i=0; i < billy.length; i++) billy[i] = i * 2; // write out array as a series of header level 6 for(i=0; i < billy.length; i++) document.write("<h6>" + billy[i] +"</h6>)"; // now fill array with 10, 15, 20, 25, 30 - see the trick?!! billy[0] = 10; for(i=1; i < billy.length; i++) billy[i] = billy[i-1] + 5; // adds 5 to the PREVIOUS ELEMENT in the array </script>


4. LOOP through numbers 0-99, put the numbers in an ARRAY and print with document.write() <script type="text/javascript"> // variable used as an index var i=0; // declare an array - indexes go from 0-99 // name of the array is "list" var list = new Array(100); // loop thru numbers 0-99, double the number and put that number an array slot // [0][2][4][6] ... [196][198] do { list[i] = i*2; // put the number INTO the array i++; }while( i <= 100 ); // print out first 5 numbers in array for (i=0; i< 5; i++) document.write(list[i] + " "); document.write("<br />"); // print out last 5 numbers in array for (i=95; i< 100; i++) document.write(list[i] + " "); document.write("<br />"); </script>


5. PROMPT & fill an ARRAY with RANDOM numbers and print contents in color <script type="text/javascript"> var size = prompt("Enter the size of the array"); var list = new Array(size); // fill array for (i=0; i< size; i++) list[i] = Math.random(); // number from 0 upto, but not including 1 // print out numbers in array in color for (i=0; i< size; i++) document.write("<span style='color:red'>" + list[i] + " <br /></span>"); document.write("<br />"); // fill array again for (i=0; i< size; i++) list[i] = Math.random() * 100; // number from 0 upto not including 100 // print out numbers in array in color for (i=0; i< size; i++) document.write("<span style='color:red'>" + list[i] + " <br /></span>"); document.write("<br />"); </script>