簡體   English   中英

如何循環一個數組,循環時間是數組長度/大小的兩倍

[英]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);

但我想增加微調器的運行時間,更簡單的方法是再次復制和粘貼這些行並增加延遲時間參數。 但是,我試圖通過使用循環來縮短它並提出這個(只是測試數組中的 output,尚未在循環中實現 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 次循環運行時 output 未定義。 是否可以將這些代碼放入循環中?

提前謝謝你。

實際上,您可以使用字符串,因為字符串是可迭代的。

 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
}

當一個操作數除以第二個操作數時,余數運算符 (%) 返回剩余的余數。

您可以在此處了解有關此運算符的更多信息: 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]); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM