双“每个”循环查找数组中的最小值
我正在尝试实现 Pinterest 墙,如下所述: 如何复制 pinterest.com 的绝对 div 堆叠布局
无论如何,我陷入了需要找到数组中最小值的索引,但同时添加我的当前块的高度到该值(因此最小值并不总是相同)。
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;
});
每次,最小值应该不同,因为我将高度添加到前一个最小值(所以它不再是最小值)。
但在我的测试中,它保持不变。
I'm trying to implement the Pinterest wall, as described here : how to replicate pinterest.com's absolute div stacking layout
Anyway, I'm stuck at one point where I need to find the index of the smallest value in an Array, but at the same time, add the height of my current block to that value (so that the smallest value isn't always the same).
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;
});
Each time, the smallest value should be different because I add the height to the previous smallest value (so it's not the smallest value anymore).
But in my tests, it remains the same.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个代码。它使用原生的 Math.min 函数,而不是低效的 jQuery 循环:
首先,Math.min() 获取所有网格元素中的最小数字。然后,使用
grid.indexOf()
来查找该元素的位置。最后,将高度添加到网格中索引index
处的元素。Try this code. It uses the native
Math.min
function, rather than a inefficient jQuery loop:First,
Math.min()
gets the lowest number out of all grid elements. Then,grid.indexOf()
is used to find the position of this element. Finally, the height is added to the element in grid at indexindex
.