从指定索引反向循环获取数组指定长度的元素
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:
- 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).
- Starting Position Calculation:
- For a 1-based index, the element before it is at
index - 2in 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.lengthbefore taking modulo ensures we never get a negative index (critical for whenindex=1).
- For a 1-based index, the element before it is at
- Circular Backward Traversal: Each iteration adds the current element to the result, then moves back one position. Using
(currentPos -1 + arr.length) % arr.lengthensures 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), adds9→ Output:[9] - Input
index=1,length=2→ Adds9, then moves to position7 → Output:[9,8] - Input
index=9,length=2→ Starts at position7 (element8), then moves to position6 → Output:[8,7] - Input
index=3,length=5→ Starts at position1 (element2), 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

