如何获取数组中的下几个元素,但在传递最后一个元素时跳回到开头?
想象一下,我有以下简单的数组:
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);
使用切片的另一种方法
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);