Home  >  Article  >  Web Front-end  >  Example analysis of random sorting of javascript array_javascript skills

Example analysis of random sorting of javascript array_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:49:25917browse

The example in this article describes how to implement random sorting of javascript arrays. Share it with everyone for your reference. The details are as follows:

We will test the random ordering of 0-9 and generate data first

var arr=[9,3,1,2,5,8,4,7,6,0];
arr.sort();
document.write("正常排序后的数组元素:"+arr.join(",")+"<BR />");

Array elements after normal sorting: 0,1,2,3,4,5,6,7,8,9
Define a random function to randomly return positive or negative numbers. The sort function will determine whether the two values ​​are in positive or negative order based on the positive and negative numbers returned randomly

function randomSort(a, b){
  return Math.random() - 0.5;
}
arr.sort(randomSort);
document.write("随机排序后的数组元素:"+arr.join(",")+"<BR />");

Randomly sorted array elements: 3,1,7,4,8,6,2,0,9,5

Randomly sorted array elements: 8,3,1,9,5,0,7,6,4,2

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn