JS immediately breaks the array implementation code _ javascript tips-js tutorial

Source: Internet
Author: User
When using javascript, values are occasionally used, and the values are disrupted. This article introduces a method to efficiently disrupt arrays, for more information, see this method.

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 an array. This is recommended. // Var arr = new Array () is not recommended ();
This sentence does not need to be explained.
For (var I = 0; I <100; I ++) {arr [I] = I;} // cyclically assign values to the array
The key is coming.

The Code is as follows:


Code
Arr. sort (function () {return 0.5-Math. random ()})
// Sort sorts arrays.
// It works like this. Select two numbers from the array each time for calculation.
// If the input parameter is 0, the two locations remain unchanged.
// If the parameter is smaller than 0, the switch location
// If the parameter is greater than 0, the position is not exchanged.
// Compare it with the next one using the big number just now. In this way, sort by loop.
/* Exactly. We have used this operation to use 0.5-Math. random. The result is either greater than 0 or less than 0. In this way, the location is either exchanged or not exchanged. Of course, a value greater than or less than 0 is immediately displayed. So the array is sorted immediately. */


The following two sentences are output to you. Haha.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.