如何循环一个数组,循环时间加倍数组 length/size

How to loop an array with loop time double the array length/size

我如何循环遍历其中包含固定元素的字符数组(在我的例子中是数组中的 4 个项目)n 次(因为 n 可以更改)?我正在尝试使用 setTimeout 和 \r 制作微调器,初始代码是:

setTimeout(() => {
  process.stdout.write('\r|   ');
}, 100);

setTimeout(() => {
  process.stdout.write('\r/   ');
}, 300);

setTimeout(() => {
  process.stdout.write('\r-   ');
}, 500);

setTimeout(() => {
  // Need to escape the backslash since it's a special character.
  process.stdout.write('\r\   '); 
}, 700);

但我想增加微调器的 运行ning 时间,更简单的方法是再次复制和粘贴这些行并增加延迟时间参数。但是,我试图通过使用循环来缩短它并提出这个(只是测试数组的输出,尚未在循环中实现 setTimeout):

const char = ['|', '/', '-', '\'];
// want to repeat the char 2 times for longer run
const nRun = char.length * 2;
for (let i = 0; i < nRun; i++){
  console.log(char[i]);
}

但是 array.length 只有 4,如果我这样做,它会在循环中第 5->8 次输出 undefined 运行。是否可以将这些代码放入循环中?

先谢谢你。

实际上您可以使用字符串,因为字符串是可迭代的。

const char = '|/-\';
// want to repeat the char 2 times for longer run
const nRun = char.length * 2;
for (let i = 0; i < nRun; i++){
  console.log(char[i%4]);
}

您还可以对从字符串转换而来的数组使用 .forEach():

    const char = '|/-\';
    for (let i = 0; i < 2; i++) Array.from(char).forEach((c,j) => setTimeout(()=>console.log(c),i*1000+j*250));

您必须使用余数运算符 (%) 才能像环一样在数组中循环:

const char = ['|', '/', '-', '\'];
// want to repeat the char 2 times for longer run
const nRun = char.length * 2;
for (let i = 0; i < nRun; i++){
  console.log(char[i % 4]); // <= change here
}

The remainder operator (%) returns the remainder left over when one operand is divided by a second operand.

您可以在此处了解有关此运算符的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder

使用了其他答案 %4

或者你可以将数组加倍:

char = char.concat(char)

let char = ['|', '/', '-', '\'];
// want to repeat the char 2 times for longer run
const nRun = char.length * 2;
char = char.concat(char)
for (let i = 0; i < nRun; i++){
  console.log(char[i]);
}