gpt4 book ai didi

javascript - 如何获取数组中的下几个元素,但在传递最后一个元素时跳回到开头?

转载 作者:行者123 更新时间:2023-12-03 17:44:13 28 4
gpt4 key购买 nike

想象一下,我有以下简单的数组:

const myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"];
现在我想在“el5”(索引4)之后获取下一个例如3个元素。如您所见,数组中只剩下 2 个元素。当命中数组中的最后一个索引时,我想回到起点并继续。
这应该是开始为“el5”(索引 4)时的预期输出: ["el6", "el7", "el1"] .
这就是我到目前为止所尝试的。

const myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"];
let output = [];

const followingElementsCount = 3;
let startIndex = myArr.findIndex(el => el === "el5") + 1;
let overflow = 0;
for (let i = 0; i < followingElementsCount; i++) {
if (startIndex + i >= myArr.length) {
startIndex = 0;
overflow++;
}

output.push(myArr[startIndex + i + overflow]);
}

console.log(output);

我不敢相信,但我无法解决这个可能相当简单的问题。

最佳答案

您可以调整数组长度的剩余部分。

const
array = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"],
output = [],
followingElementsCount = 3,
index = array.findIndex(el => el === "el5") + 1;

for (let i = 0; i < followingElementsCount; i++) {
output.push(array[(index + i) % array.length]);
}

console.log(output);

使用 slice 的另一种方法

let
array = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"],
count = 3,
index = array.findIndex(el => el === "el5") + 1,
output = [
...array.slice(index, index += count),
...(index >= array.length ? array.slice(0, index % array.length) : [])
];

console.log(output);

使用双倍长度的更短的方法。

let
array = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"],
count = 3,
index = array.findIndex(el => el === "el5") + 1,
output = [...array, ...array].slice(index, index + count);

console.log(output);

关于javascript - 如何获取数组中的下几个元素,但在传递最后一个元素时跳回到开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67130593/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com