Javascript array random sorting instance analysis and javascript instance analysis
This article describes how to implement random sorting of javascript arrays. Share it with you for your reference. The details are as follows:
We will test the random sorting of 0-9, Mr into data
Var arr = [9, 3, 1, 2, 5, 8, 4, 7, 6, 0]; arr. sort (); document. write ("array elements after normal sorting:" + arr. join (",") + "<BR/> ");
Array elements after normal sorting: 0, 1, 2, 3, 4, 5, 6, 8, 9
Define a random function that returns positive or negative numbers at random. The sort function determines whether the two values are in positive or reverse order based on the positive or negative values returned by random.
Function randomSort (a, B) {return Math. random ()-0.5;} arr. sort (randomSort); document. write ("array elements after random sorting:" + arr. join (",") + "<BR/> ");
Array elements after random sorting: 3, 1, 7, 4, 8, 6, 2, 0, 9, 5
Array elements after random sorting: 8, 3, 5, 0, 7, 6, 4, 2
I hope this article will help you design javascript programs.