Home > Web Front-end > JS Tutorial > JS immediately disrupts the array implementation code_javascript skills

JS immediately disrupts the array implementation code_javascript skills

WBOY
Release: 2016-05-16 17:47:41
Original
1397 people have browsed it

This method is the most efficient I have seen.

Copy code The code is as follows:

var arr=[];
for(var i=0;i<100;i ){
arr[i]=i;
}
arr.sort(function(){ return 0.5 - Math.random() })
var str=arr.join();
alert(str);

Code explanation:
var arr=[];//Create a new array. This is the recommended way. //It is not recommended to use var arr=new Array();
No need to explain this sentence.
for(var i=0;i<100;i ){ arr[i]=i; }//Loop to assign values ​​to the array
The key point is here
Copy code The code is as follows:

Code
arr.sort(function(){ return 0.5 - Math.random() })
//sort is to sort the array
//This is how it works. Each time, two numbers are selected from the array for operation.
//If the parameter passed in is 0, the positions of the two numbers remain unchanged.
//If the parameter is less than 0, swap the position
//If the parameter is greater than 0, do not swap the position
//Next, use the larger number just now to compare with the next one. Sort in this way.
/*Just right. We take advantage of this and use 0.5 - Math.random. The result of this operation is either greater than 0 or less than 0. In this way, the positions are either swapped or not. Of course, greater than or less than 0 appears randomly. So the array is sorted immediately. */

The last two sentences are output for you to see. hehe.
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