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

从指定索引反向循环获取数组指定长度的元素

Fixing the Array Reverse Traversal with Circular Wrap

Got it, let's get this sorted! Your current code is only pulling elements from the end of the array, ignoring the index input entirely. We need to adjust it to start at the position before your specified 1-based index, then traverse backward (with circular wrapping around the array) to collect the required number of elements.

The Problem with the Original Code

The loop in your current script starts at the last element of the array and counts backward, which is why it never uses the index value. We need to rework the logic to respect the starting position defined by your input.

Corrected Code

First, here's the updated JavaScript (the HTML can stay mostly the same, I just tweaked the label for better accessibility):

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div>
    <label for="index">Index (1-9 only)</label>
  </div>
  <input type="text" id="index" placeholder="index" />
  <input type="text" id="length" placeholder="length" />
  <button>Print</button>
</div>

JavaScript

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$('button').click(function() {
    // Convert inputs to integers (val() returns strings)
    var index = parseInt($('#index').val(), 10);
    var length = parseInt($('#length').val(), 10);
    
    // Basic input validation to avoid invalid values
    if (isNaN(index) || isNaN(length) || index < 1 || index > arr.length || length < 1) {
        console.log(`Please enter a valid index (1-${arr.length}) and positive length`);
        return;
    }
    
    var newItems = [];
    // Calculate starting 0-based position: element BEFORE the input 1-based index
    // Adding arr.length and using modulo handles the circular wrap for index=1
    var currentPos = (index - 2 + arr.length) % arr.length;
    
    for (var i = 0; i < length; i++) {
        newItems.push(arr[currentPos]);
        // Move back one position, wrap around if we hit the start of the array
        currentPos = (currentPos - 1 + arr.length) % arr.length;
    }
    
    console.log(newItems);
});

How This Works

Let's break down the key parts:

  1. Input Conversion & Validation: We convert the input values to integers and add checks to ensure they're valid (index between 1 and array length, length is a positive number).
  2. Starting Position Calculation:
    • For a 1-based index, the element before it is at index - 2 in 0-based terms (since 1-based index 1 maps to 0-based 0, so the element before is the last element of the array).
    • Adding arr.length before taking modulo ensures we never get a negative index (critical for when index=1).
  3. Circular Backward Traversal: Each iteration adds the current element to the result, then moves back one position. Using (currentPos -1 + arr.length) % arr.length ensures we wrap around to the end of the array when we reach the start.

Testing the Examples

Let's verify with your sample inputs:

  • Input index=1, length=1 → Starts at position 8 (0-based), adds 9 → Output: [9]
  • Input index=1, length=2 → Adds 9, then moves to position7 → Output: [9,8]
  • Input index=9, length=2 → Starts at position7 (element 8), then moves to position6 → Output: [8,7]
  • Input index=3, length=5 → Starts at position1 (element 2), then moves to 0 (1), 8 (9),7 (8),6 (7) → Output: [2,1,9,8,7]

All of these match your expected results!

内容的提问来源于stack exchange,提问作者Jitender

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:00:51