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


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

    常用的办法是给数组原生的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(..)却没有后面的{..},居然可以这样写!而且居然正常执行!好奇特,我得去博客园问问。

  • 相关阅读:
    MySQL wrapped 连接池
    学习 memcache 心得
    memcachedb 加 memcached engine无法提高 示例检索的查询速度
    memcached+Mysql(主从) php 编程
    动态设置select与radio的默认值
    JSTL 自定义
    坦克大战 Java版
    给超链接加onclick事件
    图片查看器C#
    备份删除还原数据库
  • 原文地址:https://www.cnblogs.com/shuaishuaidejun/p/7428635.html
Copyright © 2020-2023  润新知