我正在尝试从索引号 96
开始向后循环数组。
for (let i = keyToValue2.length[96] - 1; i >= 0; i--) {
console.log(keyToValue2[i])
}
这是我到目前为止的代码,我找不到任何关于此的帖子。 另外,这是我的第一篇文章,如果我没有正确输入代码,抱歉。
最佳答案
您不需要对数组进行切片(它会使用额外的内存,因为它会创建一个新数组)来执行此操作。
您所描述的是一个从 index = 96
开始直到到达 0
的循环,逐一减少 index
。
因此您只需将 let i = keyToValue2.length[96] - 1
更改为 let i = 96
。
这是一个使用具有 32
值的数组并从索引 16
开始向后记录它们的示例。只是使用这些值,因为 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])
}
如果您想确保索引 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])
}
关于javascript - 如何从某个索引点向后循环数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61626449/