Home > Article > Web Front-end > An example of JS implementing random sorting function
This article mainly introduces the random sorting function algorithm implemented by JS, and analyzes javascriptcommonly used sorting algorithm implementation techniques based on specific examples. Friends in need can refer to the following
The example in this article describes the random sorting function algorithm implemented by JS. Share it with everyone for your reference, the details are as follows:
Use JS to write a method to randomly arrange the elements in the array every time they are refreshed
Method 1:
var arr =[1,2,3,4]; var t; for(var i = 0;i < arr.length; i++){ var rand = parseInt(Math.random()*arr.length); t = arr[rand]; arr[rand] =arr[i]; arr[i] = t; } console.log(arr);
Method two:
var arr =[1,2,3,4]; var brr = []; var num = arr.length; for (var i = 0; i < num; i++){ var temp = parseInt(Math.random()*(num-i)); brr.push(arr[temp]); arr.splice(temp,1); } console.log(brr);
Method three:---best way.
function randomsort(a, b) { return Math.random()>.5 ? -1 : 1; //通过随机产生0到1的数,然后判断是否大于0.5从而影响排序,产生随机性的效果。 } var arr = [1, 2, 3, 4, 5]; arr.sort(randomsort);
The above is the detailed content of An example of JS implementing random sorting function. For more information, please follow other related articles on the PHP Chinese website!