由字符组成的进度条

Progressbar made of characters

我一直在尝试获得如下所示的进度条表示形式: 用户必须输入一个输入,从输入开始,循环将 运行 并达到 100%。

进入状态:70

[#######   ]  70 %
[########  ]  80 %
[######### ]  90 %
[##########] 100 %

这是我到目前为止所做的,但我现在卡住了:

let hashtag = "";
for (let i = 1; i <= 3; i++) {
  hashtag += "#";
}

console.log(
  "[" + hashtag + " ",
  " ",
  " ",
  " ",
  " ",
  " ",
  " " + "]" + " " + "30%"
);

关于如何解决这个问题的任何想法?我是个新手,请放轻松" :)

const generateOutput = (pct, width = 10) => {
  const flr = Math.floor(pct * width / 100);
  const str = "#".repeat(flr).padEnd(width, " ");
  return `[${str}] ${pct}%`;
};

// Example 90% (width 10)
console.log(generateOutput(90));

// Example 80% (width 30)
console.log(generateOutput(80, 30));

给定上述格式化字符串生成器,如果您需要一个将更改输出的循环:

const generateOutput = (pct, width = 10) => {
  const flr = Math.floor(pct * width / 100);
  const str = "#".repeat(flr).padEnd(width, "-");
  return `[${str}] ${pct}%`;
};


const EL_output = document.querySelector("#output");
const step  = 1;  // Increment step
const width = 30; // Progressbar width
const time  = 80; // Timeout ms

const progress = (val) => {
  EL_output.textContent = generateOutput(val, width);
  if (val >= 100) return; // Stop 
  setTimeout(() => progress(val += step), time);
};

// DEMO TIME! Start at 30
progress(30);
#output {white-space: pre;}
<code id="output"></code>