JavaScript中实现最高效的数组乱序方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JavaScript中实现最高效的数组乱序方法

十年灯   2020-05-13 我要评论

数组乱序的意思是,把数组内的所有元素排列顺序打乱。

常用的办法是给数组原生的sort方法传入一个函数,此函数随机返回1或-1,达到随机排列数组元素的目的。

复制代码 代码如下:

arr.sort(function(a,b){ return Math.random()>.5 ? -1 : 1;});

这种方法虽直观,但效率并不高,经我测试,打乱10000个元素的数组,所用时间大概在35ms上下(firefox)

本人一直具有打破沙锅问到底的优良品质,于是搜索到了一个高效的方法。原文见此

复制代码 代码如下:

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;
    };
}
arr.shuffle();

此方法是为Array.prototype添加了一个函数,叫shuffle——不过叫什么名字不重要啦,重要的是他的效率。

拿我上面那个10000个元素的数组来测试,用这个方法乱序完成仅需要7,8毫秒的时间。

把数组元素增加10倍到100000来测试,第一种sort方法费时500+ms左右,shuffle方法费时40ms左右,差别是大大的。

完整测试代码:

复制代码 代码如下:

var count = 100000,arr = [];
for(var i=0;i.5 ? -1 : 1;});
Array.prototype.sort.call(arr,function(a,b){ return Math.random()>.5 ? -1 : 1;});
document.write(arr+'
');
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('
'+arr+'
');
var t1 = new Date().getTime();
document.write(t1-t);

另外,大家有没有注意到shuffle代码里的for循环,他没有后半截!也就是只有for(..)却没有后面的{..},居然可以这样写!而且居然正常执行!好奇特,我得去博客园问问。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们