In recent projects encountered a demand, from a list of random display of the list of parts, the demand is small, JS is also very easy to implement. It mainly uses the random method of the Math object, and the splice method of array.
The idea is to create a new array, hold all the lists, then figure out the random number, take the value of the random index from the array, and make a random array.
The source code is as follows:
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <Metahttp-equiv= "Content-type"Content= "text/html; charset=utf-8;">5 <title>Random fetch from an array</title>6 <Metaname= "Author"content= "Rainna" />7 <Metaname= "keywords"content= "Rainna S js Lib" />8 <Metaname= "description"content= "JS" />9 </Head>Ten One <Body> A <Script> - //The total length of the count array randomcount the number of random displays - varSelrandomnum= function(count,randomcount) { the varCount=Count|| Ten; - varRandomcount=Randomcount|| 3; - - varTotalarray=[],randomarray= []; + for(varI=0, L=Count;i<L;i++){ - Totalarray.push (i); + } A for(varI=0, L=Randomcount;i<L;i++){ at varRandomindex=Math.floor (Math.random ()*totalarray.length); - varSelectindex=Totalarray.splice (Randomindex,1)[0]; - Randomarray.push (Selectindex); - } - Console.log (Totalarray+ '-----' +Randomarray); - } in - selrandomnum (); to </Script> + </Body> - </HTML>
The 8--of JS case is randomly taken from an array