简体   繁体   中英

How to loop through array backwards from certain index point

I am trying to loop through an array backwards starting from an index number of 96 .

for (let i = keyToValue2.length[96] - 1; i >= 0; i--) {
    console.log(keyToValue2[i])
}

This is my code so far and I can't find any posts about this. Also, this is my first post sorry if I didn't type code correctly.

You don't need to slice the array (which uses additional memory, as it creates a new array) to do that.

What you are describing is a loop that starts at index = 96 until it reaches 0 , decreasing index one by one.

So you just need to change let i = keyToValue2.length[96] - 1 to let i = 96 .

Here's an example using an array with 32 values and logging them backwards, starting at index 16 . Just used these values because StackOverflow snippets limit the number of log entries:

 // This creates a new array with 32 numbers (0 to 31, both included): const array = new Array(32).fill(null).map((_, i) => `Element at index ${ i }.`); // We start iterating at index 16 and go backwards until 0 (both included): for (let i = 16; i >= 0; --i) { console.log(array[i]) }

If you want to make sure the index 96 actually exists in your array, then use let i = Math.min(96, keyToValue2.length - 1 :

 // This creates a new array with 32 numbers (0 to 31, both included): const array = new Array(32).fill(null).map((_, i) => `Element at index ${ i }.`); // We start iterating at index 31 (as this array doesn't have 64 elements, it has only 32) // and go backwards until 0 (both included): for (let i = Math.min(64, array.length - 1); i >= 0; --i) { console.log(array[i]) }

Try this,

slice array up to which index you want, then loop it reverse order.

var sliced = keyToValue2.slice(0, 96);

for (let i = sliced.length - 1; i >= 0; i--) {
    console.log(keyToValue2[i])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM