让我们说我想要"数组中的6个元素仅包含3.如果到达结尾,则重新开始。
示例:
let arr = ["a", "b", "c"];
let wanted = 5;
for(let i = 0; i < wanted; i++) {
console.log(arr[i]);
}
当然会返回:
a
b
c
undefined
undefined
相反,我需要:
a
b
c
a
b
有没有办法在元素结束后从数组的开头开始?
答案 0 :(得分:11)
使用%
(Remainder)运算符获取余数。
console.log(arr[i % arr.length]);
余数值将在数组索引范围内。
例如:当i
到达
3
=&gt; 3 % 3
= 0
4
=&gt; 4 % 3
= 1
0
=&gt; 0 % 3
= 0
。
let arr = ["a", "b", "c"];
let wanted = 5;
for (let i = 0; i < wanted; i++) {
console.log(arr[i % arr.length]);
}
&#13;
答案 1 :(得分:2)
您可以使用(%) remainder运算符。它将从0开始索引,直到arr.length - 1。
第一步是
[0 % 3] === 0 whole 0 remainder,
[1 % 3] === 0 whole 1 remainder,
[2 % 3] === 0 whole 2 remainder
[3 % 3] === 1 whole 0 remainder
[4 % 3] === 1 whole 1 remainder
let arr = ["a", "b", "c"];
let wanted = 5;
for(let i = 0; i < wanted; i++) {
console.log(arr[i % arr.length]);
}
答案 2 :(得分:0)
只需使用%
let arr = ["a", "b", "c"];
let wanted = 5;
for(let i = 0; i < wanted; i++) {
console.log(arr[i % arr.length]);
}
答案 3 :(得分:0)
let arr = ["a", "b", "c"];
let wanted = 5;
for (let i = 0; i < wanted; i++) {
console.log(arr[i]);
if (arr.length == i) {
i = 0;
}
}
答案 4 :(得分:0)
if (i+1 == arr.length){
console.log(arr[i]);
i=0;
wanted =wanted-arr.length;
}else{
console.log(arr[i]);
}
循环将正常工作,直到你的计数器位于最后一个元素, 然后它将重置为0以重新开始,并将继续执行此操作,直到达到所需的元素数量。