Home > Web Front-end > JS Tutorial > body text

Example analysis of random sorting of javascript array_javascript skills

WBOY
Release: 2016-05-16 15:49:25
Original
918 people have browsed it

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 />");

Copy after login

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 />");

Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!