»
EnglishFrenchVietnamese

Print - Array Randomizer - JavaScriptBank.com

Full version: jsB@nk » Calculation » Array Randomizer
URL: https://www.javascriptbank.com/array-randomizer-erichood.html

Array Randomizer © JavaScriptBank.comThis is an example of using the Array() object's own sort method to randomize itself. Very simple and clean! Example of how to randomize an array.

Full version: jsB@nk » Calculation » Array Randomizer
URL: https://www.javascriptbank.com/array-randomizer-erichood.html



HTML
<SCRIPT language=JavaScript><!--//'--Following demonstrates the randomize array concept.//'--If you like this, send me an email and say hello!//'[email protected] myArray=new Array(), max=0//'--Ask for a number > 0while (max<1){max=parseInt(prompt("Please designate an array length : ", 20))if (isNaN(max)) max=0}//'--Create an ordered array of length max//'--1st element = 1, 2nd element = 2, 3rd element = 3, etc..for (i=0; i<max; myArray[i]=++i);//'--Display the ordered array document.write("<BR>Ordered array:<BR>")document.write(myArray)//'-------------------------------------------------------//'-------------------------------------------------------//'--NOTE: To randomize an array is //'--  to sort the array ... randomly//'--Return random +1 or -1function RandomCompare() { return (Math.random()<.5?1:-1) }myArray.sort(RandomCompare)//'-------------------------------------------------------//'-------------------------------------------------------//'--Now display the array after being randomized.document.write("<BR>Random array:<BR>")document.write(myArray)//--></SCRIPT><!--    This script downloaded from www.JavaScriptBank.com    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com-->