如何从特定索引点向后遍历数组

时间:2020-05-06 02:40:43

标签: javascript arrays loops

我正在尝试从索引号96开始向后遍历数组。

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

到目前为止,这是我的代码,我找不到与此相关的任何帖子。 另外,如果我没有正确键入代码,这是我的第一篇帖子。

2 个答案:

答案 0 :(得分:1)

您无需对数组进行切片(因为它会创建新数组,因此会占用更多内存)。

您要描述的是一个循环,该循环从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])
}

答案 1 :(得分:0)

尝试一下,

将数组切成所需的索引,然后以相反的顺序循环。

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

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