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

JavaScript method to randomly rearrange arrays_javascript skills

WBOY
Release: 2016-05-16 15:49:27
Original
1165 people have browsed it

The example in this article describes how JavaScript randomly rearranges an array. Share it with everyone for your reference. The details are as follows:

Two methods are provided here to randomly rearrange the array.

<script>
var count = 100000,arr = [];
for(var i=0;i<count;i++){
 arr.push(i);
}
//常规方法,sort()
var t = new Date().getTime();
Array.prototype.sort.call(arr,function(a,b){ return Math.random()>.5 &#63; -1 : 1;});
document.write(arr+'<br/>');
var t1 = new Date().getTime();
document.write(t1-t);
//以下方法效率最高
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;
  };
}
var t = new Date().getTime();
arr.shuffle();
document.write('<br/>'+arr+'<br/>');
var t1 = new Date().getTime();
document.write(t1-t);
</script>

Copy after login

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!