简化随机订单jQuery函数

Streamline random-order jQuery functions

本文关键字:jQuery 函数 随机      更新时间:2023-09-26

冒险进入随机排序的世界,在尽可能高效地组合一些函数时遇到了困难一切正常,但我有一种新手的感觉,因为我用在Stack Overflow上找到的两个函数构建了它,我修改了这两个函数,然后把它们放在一起。

我希望您能为我提供任何简化代码以提高效率和消除冗余的方法

此函数获取10个div,将它们重新排列为随机顺序,然后以额外的随机顺序将该随机顺序依次淡入页面。效果很好,请看这里:http://jsfiddle.net/danielredwood/MgFj2/

非常感谢你的帮助!

__初始化页面上的功能

$(document).ready(function(){
    shuffle();
});

__创建淡入淡出顺序的阵列

function introfade(x) {
    var o = [];
    for (var i = 0; i < x; i++) {
        var n = Math.floor(Math.random()*x);
        if ( $.inArray(n, o) > 0 ) {
            --i;
        } else {
            o.push(n);
        }
    }
    return o;
}

__重新排列div并在中使其褪色

function shuffle() {
    var b       = $('.box'),
        arrange = $('<div>'),
        size    = b.size(),
        fade    = introfade(size);
    while (size >= 1) {
        var rand = Math.floor(Math.random() * size),
            temp = b.get(rand);
        arrange.append(temp);
        b = b.not(temp);
        size--;
    }
    $('.main').html(arrange.html());
    $('.box').each(function(i) {
        var c = $(this);
        setTimeout(function() {
            c.fadeTo(500, 1);
        }, fade[i]*150);
    });
}

我看到了一个优化。与其随机选择一个数字,然后检查它是否在o中,不如制作一个可能值的数组(a),然后随机将splice()取一,并将其附加到o中。这种方式总是需要x步骤。另一种方法可能需要两倍多的时间,尤其是当o几乎满了时,你很有可能生成一个已经在o中的数字,尤其是随着x的大小增加。

function introfade(x) {
    var o = [];
    var a = [];
    for(var i=0; i<x; i++) {
         a.push(i);           
    }
    for(var i=x; i>0; i--) {
        var n = Math.floor(Math.random()*i);
        o.push(a.splice(n,1)[0]);           
    }
    return o;
}

http://jsfiddle.net/8Jy8T/

另一种方法是遍历数组,并用另一个随机条目交换条目:

function introfade(x) {
    var o = [];
    for(var i=0; i<x; i++) {
         o.push(i);           
    }
    for(var i=0; i<x; i++) {
        var n = Math.floor(Math.random()*i);
        var tmp = o[n];
        o[n] = o[i];
        o[i] = tmp;      
    }
    return o;
}

我一直在使用"由内而外"的算法来处理这类事情。这是我的实现:

/** pushRand
    Insert a value into an array at a random index. The element 
    previously at that index will be pushed back onto the end. 
    @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm
    @param {Array} array Array to insert into.
    @param {Mixed} value Value to insert.
    @param {Object} rng Optional RNG. Defaults to Math.
    @return {Number} The new length of the array.
*/
function pushRand (array, value, rng) {
    var j = (rng || Math).random() * (array.length + 1) | 0;
    array.push(array[j]);
    array[j] = value;
    return array.length;
}

使用这个,你的代码可以简化一点:

// Create array for fade order
function introfade(x) {
    var o = [];
    while (x--) pushRand(o, x);
    return o;
}
// Rearrange divs and fade them in
function shuffle() {
    var b       = $('.box'),
        main    = $('.main')[0],
        arrange = $('<div>'),
        size    = b.size(),
        fade    = introfade(size),
        boxes   = [], 
        i;
    for (i = size; i--;) pushRand(boxes, b[i]);
    for (i = size; i--;) main.appendChild(boxes[i]);
    b.each(function(i) {
        var c = $(this);
        setTimeout(function() {
            c.fadeTo(500, 1);
        }, fade[i]*150);
    });
}

看看这里:http://jsfiddle.net/MgFj2/2/

为了好玩,我会在这里抛出另一个答案。。。您可以用相当少量的jQuery:来实现这一点

// Rearrange divs and fade them in
function shuffle() {
    var num = $('.box').length - 1;
    $('.box').each(function(i) {
        var rand = Math.floor(Math.random() * num);
        $(this).remove().insertAfter($('.box').eq(rand)).delay(i * 50).fadeTo(250, 1);
    });
}
// Initialize function
$(document).ready(function() {
    shuffle();
});

http://jsfiddle.net/gvjrr/

这就是全部。这略有不同,因为它按顺序淡出div(但它们在页面中被打乱)。如果你想继续随机淡出它们,你只需先洗牌而不暴露,然后洗牌再暴露:

// Rearrange divs and fade them in
function shuffle() {
    var num = $('.box').length-1;
    $('.box').each(function(i) {
        var rand = Math.floor(Math.random() * num);
        $(this).remove().insertAfter($('.box').eq(rand));
    })
    $('.box').each(function(i) {
        var rand = Math.floor(Math.random() * num);
        $(this).remove().insertAfter($('.box').eq(rand)).delay(i * 50).fadeTo(250, 1);
    });
}
// Initialize function
$(document).ready(function() {
    shuffle();
});

http://jsfiddle.net/AapCP/1/

你也许可以进一步简化它。