JS scrambled Array

Source: Internet
Author: User

JS, to disrupt the array there are many ways, online spread a foreign people write method, I think is the most concise:

function Randomsort (A, b) {
Return Math.random () >.5? -1:1;//uses the Math.random () function to generate random numbers between 0~1 and 0.5, and returns-1 or 1
}
var arr = [1, 2, 3, 4, 5];
Arr.sort (Randomsort);

Here's a description of the next sort () function, in which a function is built into the array object in JS:

Arrayobj.sort ([sortfunction])

This method sorts the array object appropriately, and does not create a new array object during execution.

Sortfunction is optional.

is the name of the function used to determine the order of elements. If this argument is omitted, then the elements are sorted in ascending order in ASCII characters.
The Sortfunction method has two parameters. Represents each of the two array entries for each sort comparison. Sort () performs this argument each time the comparison of two array entries is performed and passes the two comparison array items as arguments to the function. The order of two array items is exchanged when the function returns a value of 1, otherwise it is not exchanged.

We can make a slight change to the above Randomsort () to achieve ascending and descending order:


Return a < b? -1:1;//If the a<b is not exchanged, the exchange, that is, ascending order
}


Return a > B? -1:1;;/ /If the a>b does not exchange, otherwise exchange, will arrange the order
}

Alternatively, a nameless function can be directly placed in a call to the sort () method. The example below is an odd number in front and an even number in the following example:

The following is a reference fragment:






Document.writeln (ARRA); Output: 1,5,3,4,6,2

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.