简体   繁体   English

如何多次遍历数组项

[英]how to loop through array items multiple times

So, if I wanted to log the numbers one to five once, I might write something like: 所以,如果我想将数字记录一到五次,我可能会写一些类似的东西:

var array = [1,2,3,4,5]

function loop(n) {
  for (var i=0;i<n;i++) {
    console.log(array[i])
  }
}

loop(5)

but how would I log the numbers one to five more than once? 但我如何不止一次记录数字1到5?

eg writing loop(10); 例如,写循环(10); to get the following result: 1 2 3 4 5 1 2 3 4 5 得到以下结果:1 2 3 4 5 1 2 3 4 5

Obviously at the moment I get 'undefined' for anything above loop(5) 显然,目前我对循环上的任何事情都有“未定义”(5)

Use the remainder operator : 使用余数运算符

function loop(n) {
  for (var i=0;i<n;i++) {
    console.log(array[i%array.length])
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM