简体   繁体   English

如何从某个索引点向后循环数组

[英]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 .我试图从索引号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.您不需要对数组进行切片(它使用额外的 memory,因为它会创建一个新数组)来执行此操作。

What you are describing is a loop that starts at index = 96 until it reaches 0 , decreasing index one by one.您所描述的是一个循环,从index = 96开始,直到它到达0index一个接一个递减。

So you just need to change let i = keyToValue2.length[96] - 1 to let i = 96 .因此,您只需将let i = keyToValue2.length[96] - 1更改为let i = 96

Here's an example using an array with 32 values and logging them backwards, starting at index 16 .这是一个使用具有32值的数组并将它们向后记录的示例,从索引16开始。 Just used these values because StackOverflow snippets limit the number of log entries:只使用这些值是因为 StackOverflow 片段限制了日志条目的数量:

 // 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 :如果要确保数组中确实存在索引96 ,请使用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])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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