将'each'循环加倍以查找Array中的最小值

时间:2011-10-16 19:34:30

标签: jquery each

我正在尝试实现Pinterest墙,如下所述:how to replicate pinterest.com's absolute div stacking layout

无论如何,我陷入了一个需要在数组中找到最小值索引的点,但与此同时,当前块的高度添加到该值(以便最小值并不总是相同)。

var grid = new Array(4); // 4 as example

// Add values to the Array
$.each(grid, function(j) {
    grid[j] = j;
});
var smallest_index = 0;
var smallest_value = grid[0];

// Find the index of the smallest value in the Array
SmallestValueIndex = function() {
    $.each(grid, function(i, v) {
        if (v < smallest_value) {
            smallest_index = i;
            smallest_value = v;
        }
    });
}

// Go through all my '<div>' and add the height to the current smallest value
$.each(blocs, function() {
    SmallestValueIndex();
    var h = $(this).height();
    grid[smallest_index] += h;
});

每次,最小值应该不同,因为我将高度添加到之前最小值(因此它不再是最小值)。

但在我的测试中,它仍然是相同的。

1 个答案:

答案 0 :(得分:2)

试试这段代码。它使用本机Math.min函数,而不是低效的jQuery循环:

$.each(blocs, function() {
    var lowest = Math.min.apply(null, grid);
    var index = grid.indexOf(lowest);
    grid[index] += $(this).height();
}

首先,Math.min()获取所有网格元素中的最小数字。然后,grid.indexOf()用于查找此元素的位置。最后,高度将添加到索引为index的网格中的元素。

相关问题