gpt4 book ai didi

javascript - 如何根据起始索引循环/环绕数组?

转载 作者:行者123 更新时间:2023-11-28 14:27:02 25 4
gpt4 key购买 nike

var ZODIAC = ["RAT", "OX", "TIGER", "RABBIT", "DRAGON", "SNAKE", "HORSE", "SHEEP", "MONKEY", "ROOSTER", "DOG", "PIG"];
var STARTING_ZODIAC = "MONKEY";

如何打印该数组中以 Monkey 开头并以 Sheep 结尾的所有元素?

最佳答案

您可以使用模运算符,以便索引变量在达到 ZODIAC 数组的长度后回绕到 0:

const ZODIAC = ["RAT", "OX", "TIGER", "RABBIT", "DRAGON", "SNAKE", "HORSE", "SHEEP", "MONKEY", "ROOSTER", "DOG", "PIG"];
const STARTING_ZODIAC = "MONKEY";
const startIndex = ZODIAC.indexOf(STARTING_ZODIAC);

console.log(STARTING_ZODIAC);
for (let i = startIndex + 1; i !== startIndex; i = (i + 1) % ZODIAC.length) {
console.log(ZODIAC[i]);
}

另一种方法是先将数组的两部分切片成正确的顺序:

const ZODIAC = ["RAT", "OX", "TIGER", "RABBIT", "DRAGON", "SNAKE", "HORSE", "SHEEP", "MONKEY", "ROOSTER", "DOG", "PIG"];
const STARTING_ZODIAC = "MONKEY";
const startIndex = ZODIAC.indexOf(STARTING_ZODIAC);

[
...ZODIAC.slice(startIndex),
...ZODIAC.slice(0, startIndex)
].forEach(str => console.log(str));

关于javascript - 如何根据起始索引循环/环绕数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52883995/

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