Beh*_*oth 7 javascript arrays loops
想象一下,我有以下简单的数组:
const myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"];
Run Code Online (Sandbox Code Playgroud)
现在我想在“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);Run Code Online (Sandbox Code Playgroud)
我不敢相信,但我无法解决这个可能相当简单的问题。
您可以调整数组长度的其余部分。
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);Run Code Online (Sandbox Code Playgroud)
使用切片的另一种方法
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);Run Code Online (Sandbox Code Playgroud)
使用双倍长度的更短方法。
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);Run Code Online (Sandbox Code Playgroud)
你应该把你的数组变成循环数组。在像 Haskell 这样的函数式语言中,这对于指令来说是一件轻而易举的事cycle [2, 5, 7],它会给出一个无限的列表, [2, 5, 7, 2, 5, 7, ...]让你不用担心它的结束。由于 Haskell 本质上是懒惰的,所以我们不关心列表是无限的。
因此,在 JS 中,您可以通过打开数组的index模块化来轻松模仿这个不错的功能。length因此,一个简单的函数就足以提供一个优雅的解决方案。
function collectCyclicFromIndex(i,n,a){
return Array.from({length:n}, (_,j) => a[(i+j)%a.length])
};
myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"];
console.log(collectCyclicFromIndex(5,3,myArr));
console.log(collectCyclicFromIndex(2,13,myArr));Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {
max-height: 100% !important
}Run Code Online (Sandbox Code Playgroud)