Lau*_*ent 1 javascript node.js
假设我"想要"来自仅包含3的数组中的6个元素.如果到达结束,则重新开始.
例:
let arr = ["a", "b", "c"];
let wanted = 5;
for(let i = 0; i < wanted; i++) {
console.log(arr[i]);
}
Run Code Online (Sandbox Code Playgroud)
当然会返回:
a
b
c
undefined
undefined
Run Code Online (Sandbox Code Playgroud)
相反,我需要:
a
b
c
a
b
Run Code Online (Sandbox Code Playgroud)
有没有办法在元素结束后从数组的开头开始?
Pra*_*lan 11
console.log(arr[i % arr.length]);
Run Code Online (Sandbox Code Playgroud)
余数值将在数组索引范围内.
例如:i到达时
3=> 3 % 3=04=> 4 % 3=10=> 0 % 3= 0.let arr = ["a", "b", "c"];
let wanted = 5;
for (let i = 0; i < wanted; i++) {
console.log(arr[i % arr.length]);
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |