Home > Article > Web Front-end > JS randomly sorted array example analysis
This article mainly introduces the JS random sorting array implementation method, and combines specific examples to compare and analyze the relevant operating techniques of javascript for random sorting of arrays. Friends who need it can refer to it. I hope it can help everyone.
When doing random display of recommended ads, I needed to randomly sort the data array, so I wrote one, as follows:
function randomOrder (targetArr) { var originalArr = targetArr; var newArr = []; var arrLength = targetArr.length; var j = -1; var tmpObj = {}; for(var i = 0;i < arrLength;i++){ while(true) { if(tmpObj[j = parseInt(arrLength * Math.random())] == undefined) { tmpObj[j] = 1; console.log(j); break; } } newArr[i] = originalArr[j]; } return newArr; }
But... later on the Internet When I saw the method written by the master, I felt that I was instantly killed to the point where nothing was left, as follows:
function sortNumber(a,b) { return Math.random() - 0.5; } var arr = arr=[9,3,1,2,5,8,4,7,6,0]; arr.sort(sortNumber);
Have you mastered it? Collect it if you find it useful.
Related recommendations:
Adding weight factors to PHP random sorting
Introduction to examples of JS implementing random sorting function
php array random sorting example
The above is the detailed content of JS randomly sorted array example analysis. For more information, please follow other related articles on the PHP Chinese website!