Javascript Random Value

<script type="text/javascript">
KeywordArray = new Array(5); //Create Array with 5 options
KeywordArray[0] = "John";  // Option begin at 0 not 1
KeywordArray[1] = "Matt";
KeywordArray[2] = "Mike";
KeywordArray[3] = "Josh";
KeywordArray[4] = "David";
var randno = Math.floor ( Math.random() * KeywordArray.length ); //call variable from a random number(up to 5)
document.write(KeywordArray[randno]); //render code
</script>

Key Term Brakedown:
KeywordArray – Is just the name of the array and came be changes at will as long as instances of the name are change as well.

new Array – Built in function of JavaScript to group multiple values.

Array(#) – as JavaScript savvy people may notice the code is written out and not in shorthand. Shorthand, being writing all the values(options) between the “( )” where the # is but in this case the # is used to do math later in the function so the array needs to be written out fully.

KeywordArray[#] = “” – This the listing of all the values starting a 0 and adding up to the about you need. So if you have 5 values then you have 0 – 4 listings. Inside the “quotes” is the information you want to display.

var randno = Math.floor ( Math.random() * KeywordArray.length );
I separated the section because this is where the first part of the function happens. Brake down: var variable name = round number down ( random number within the length[amount of values] of the array );

document.write(KeywordArray[randno]);
Finally the second half where the information is writen. Brakedown: webpage.render content on page(array[number of selected option]);







Leave a Reply