javascript - 当循环中没有更多元素时如何重新开始?

标签 javascript node.js

假设我“想要”一个仅包含 3 个元素的数组中的 6 个元素。如果到达末尾,则重新开始。

例子:

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

有没有办法在元素结束后从数组开头开始?

最佳答案

使用 %(Remainder) 得到余数运营商。

console.log(arr[i % arr.length]);

余数将在数组索引范围内。

例如:当i到达

  • 3 => 3 % 3 = 0
  • 4 => 4 % 3 = 1
  • 0 => 0 % 3 = 0

let arr = ["a", "b", "c"];
let wanted = 5;

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

关于javascript - 当循环中没有更多元素时如何重新开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42828297/

相关文章:

javascript - 如何在 Node.js 中实现递归 Promise 调用

javascript - Express 正在提供 index.html 而不是我的 Webpack 包。我的配置文件有问题吗?

javascript - 无法遍历依赖图 : Cannot find module './crypto_auth' sodium-universal

c# - 在 JS 和 C# 中通过 POST 请求解析 JSON 数据

javascript - 基于自动分号插入JS规则的有趣错误。需要说明

javascript - 根据名称渲染 React 组件

javascript - 在这种情况下,为什么 jQuery 找不到包含显示数学的 div

javascript - 一次处理 1 个包含异步函数的循环

javascript - 如何将重音字符从 JavaScript 传递到 HTML?

javascript - 用链接替换标签,它只替换字符串中的最后一个词