获取数组中的第n个项目 [英] Get every nth item in array

查看:80
本文介绍了获取数组中的第n个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML元素数组.我正在检查数组中是否存在这样的上一个对象:

I have an array of HTML elements. I'm checking whether a previous object in the array exists like this:

var boxes = $('.box'); // creating the array

boxes.each(function(i){ // going through the array
    var prevBox = i>0?$(boxes[i-1]):false; // check whether a previous box exists
    if (prevBox) { } // do something
    else { } // do something else
});

这很好.但是我还需要检查数组中每个第四个对象(框)的存在,或更确切地说,检查一个对象是否当前对象之前存在三个对象.

This works well. But I would also need to check the existence of every fourth object (box) in the array, or more precisely whether an object three objects before the current one exists.

这不起作用:

var prevBox = i>0?$(boxes[i-4]):false;

我相信使用jQuery.grep()并检查(i % 4) == 0是否可能是答案,但是由于我对Javascript的了解有限,所以我不知道如何将其应用于现有的Java.

I believe using jQuery.grep() and checking if (i % 4) == 0 might be the answer, but with my limited knowledge of Javascript, I don't know how to apply it to what I have now.

任何人都可以帮忙吗?谢谢!

Anyone can help? Thanks!

推荐答案

您可以使用模运算符,看看您是否处在第四个区间.

You can use the modulus operator in the loop to see if you are on a fourth interval.

问题已澄清.

var boxes = $('.box'); // creating the array

boxes.each(function(i){
    if( i >= 3 ) {
        var prevBox = boxes.eq( i - 3 );
        var pos = prevBox.position();
        var top = pos.top;
    }
});

这篇关于获取数组中的第n个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆