You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JS判断列表索引是否属分组内指定位置(类CSS nth选择器)

How to Check if an Index Matches :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 group
  • targetPosition = 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, ...], b is at index 1. 1 % 11 = 1, which matches our adjusted target, so this returns true.

Edge Cases to Consider

  • If selectedIndex is outside the valid range of the array, we immediately return false to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:22:03