PHP in JavaScript to implement the scrambling array function shuffle instance _javascript skill

Source: Internet
Author: User
Tags cdata shuffle javascript array

PHP has a very convenient to disrupt the array of functions shuffle (), this function in many cases will be used, but the JavaScript array does not have this method, it does not matter, you can expand A, do-it-yourself, well-clothed.

Please refresh the page to see the random sort effect.

Copy Code code as follows:

<script type= "Text/javascript" >
<! [cdata[
Description: Add Shuffle method to Javascript array

var shuffle = function (v) {
For (var j, x, i = v.length; i; j = parseint (Math.random () * i), x = V[--i], v[i] = V[j], v[j] = x);
return v;
};

var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

document.write ("a =", A.join (","), "<br/>shuffle (a) =", Shuffle (a));

]]>
</script>

Output results:

Copy Code code as follows:

A = 0,1,2,3,4,5,6,7,8,9

Shuffle (A) = 1,5,0,9,2,3,6,8,4,7
A.shuffle () = 0,4,2,8,5,1,3,6,9,7

Add a method to the array by prototype:

Copy Code code as follows:

<script type= "Text/javascript" >
<! [cdata[

var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

if (! Array.prototype.shuffle) {
Array.prototype.shuffle = function () {
For (var j, x, i = this.length; i; j = parseint (Math.random () * i), x = This[--i], this[i] = This[j], this[j] = x);
return this;
};
}

document.write ("A =", A.join (","), "<br/>a.shuffle () =", A.shuffle ());

]]>
</script>

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.