如何基于起始索引在数组中循环/换行?

时间:2018-10-18 23:41:56

标签: javascript arrays

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

如何打印此数组中从Monkey开始到绵羊结束的所有元素?

5 个答案:

答案 0 :(得分:2)

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

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]);
}

另一种方法是首先slice将数组的两个部分按正确的顺序排列:

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));

答案 1 :(得分:1)

6个答案,但没有一个答案对我有帮助:

for (let i = 0; i < ZODIAC.length; i++) {
   console.log(ZODIAC[(startIndex + i) % ZODIAC.length]);
}

循环12次,并使用模运算符,以便我们可以计算4、5,... 10、11、0、1、2、3。

答案 2 :(得分:0)

足够容易,只需从数组的开头到结尾打印,然后从数组的开头到开头打印即可。

function printZodiacs(startingZodiac, zodiacs) {
  const startIndex = zodiacs.indexOf(startingZodiac);

  // start to end of array
  for (let i = startIndex; i < zodiacs.length; i++) {
    console.log(zodiacs[i]);
  }

  // beginning of array to to start
  for (let i = 0; i < startIndex; i++) {
    console.log(zodiacs[i]);
  }
}

printZodiacs(STARTING_ZODIAC, ZODIAC);

答案 3 :(得分:0)

另一种有趣的解决方法:

let doubleZodiac = ZODIAC.concat(ZODIAC);
let start = ZODIAC.indexOf(STARTING_ZODIAC);

for (let i = 0; i < ZODIAC.length; i++) {
  console.log(doubleZodiac[start + i]);
}

这会将数组的副本添加到末尾,然后仅从起始索引打印12。

答案 4 :(得分:0)

对我来说,最直接的方法是一个do-while循环,从索引开始,然后包装直到返回该索引。在这种情况下,可以使用do块使事情保持简单:

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

let i = start_ndx = ZODIAC.indexOf(STARTING_ZODIAC);

do {
  console.log(i, ZODIAC[i++])
  i == ZODIAC.length && (i=0)
} while (i!==start_ndx)

评论:对我来说,大多数其他答案似乎都是不必要的复杂(使用模)或效率低下(复制值和新数组);从头到尾都可以避免,在我看来这更易于维护