如何用JS判断列表索引是否属分组内指定位置(类CSS nth选择器)
:nth-child(11n + 2) Without Loops Hey there! Let's break down how to solve this problem cleanly without any loops—perfect for matching that CSS-style grouping behavior.
The Core Idea
We can leverage modulo arithmetic to directly calculate the position of selectedIndex within its 11-element group. This avoids looping entirely since modulo gives us the remainder when dividing by the group length, which is exactly the offset within the current group.
Key Variables to Clarify
First, let's align on index conventions (critical here, since arrays use 0-based indexing but CSS uses 1-based):
selectedIndex: The index you're checking (we'll cover both 0-based and 1-based cases)groupLength = 11: Fixed size of each grouptargetPosition = 2: The desired position in each group (1-based, like CSS's:nth-child)listLength = X: Total number of elements in the array
Solution Code & Explanation
Case 1: 1-based Indexing (matches CSS :nth-child)
If your selectedIndex uses 1-based numbering (e.g., counting from 1 instead of 0), use this function:
function isMatchingPosition(selectedIndex, groupLength, targetPosition, listLength) { // First, validate the index is within the valid range if (selectedIndex < 1 || selectedIndex > listLength) return false; // The modulo operation gives the position within the group return selectedIndex % groupLength === targetPosition; }
- Why this works: For any index like 2, 13, 24, etc., dividing by 11 leaves a remainder of 2—exactly the target position in each group. If the index was 11, 22, etc., the remainder would be 0 (which would match
:nth-child(11n)if needed).
Case 2: 0-based Indexing (standard array indexing)
Since most programming languages use 0-based arrays, adjust the target position to 1 (since the 2nd element in a group is at index 1):
function isMatchingPosition0Based(selectedIndex, groupLength, targetPosition1Based, listLength) { // Validate the index is within the array bounds if (selectedIndex < 0 || selectedIndex >= listLength) return false; const targetPosition0Based = targetPosition1Based - 1; return selectedIndex % groupLength === targetPosition0Based; }
- Example: If your array is
[a, b, c, ...],bis at index 1.1 % 11 = 1, which matches our adjusted target, so this returnstrue.
Edge Cases to Consider
- If
selectedIndexis outside the valid range of the array, we immediately returnfalseto avoid invalid checks. - For groups where the last group has fewer than 11 elements, the modulo still works correctly—it just checks the position within the partial final group.
内容的提问来源于stack exchange,提问作者Ross Rawlins

