javascript - 如何使用 for 或 while 循环迭代到 100 并使用 javascript 显示每次迭代的总和?

标签 javascript loops for-loop while-loop iteration

只是做一个小作业。我需要迭代到 100,还需要 console.log 前面每个示例的结果。

系列示例:(1)+(1+2)+(1+2+3)+…+(1+2+3+…+n)<=100

Iteracion1=1
Iteracion2= 1+2 = 3
iteracion 3: 1+2+3 = 6
iteracion 4: 1+2+3+4 = 10

我有这个:

for (i = 0; i <= 100; i++) {
    if(i < 100) {
    console.log(`${i}+${1}`);
   }};

但我不知道如何在每次迭代中添加它的总和。如果你有这方面的任何引用资料那就太好了!谢谢。

最佳答案

您可以使用单个循环高效获得结果。

出于演示目的,我打印了最多 20。您可以添加任意数量的选择。

let lastTotal = 0;
let lastStr = "";

for (let i = 1; i <= 10; ++i) {
  const total = (lastTotal ?? 0) + i;
  const str = lastStr ? lastStr + " + " + i : i;
  console.log(`Iteration ${i}: ${str}${total === 1 ? "" : " = " + total}`);
  lastTotal = total;
  lastStr = str;
}
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何使用 for 或 while 循环迭代到 100 并使用 javascript 显示每次迭代的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69081606/

相关文章:

javascript - Next-Image Relative Paths 有效,但在抓取时指向 404 页

javascript - 有条件地延迟函数执行

java - 错误 : java. util.NoSuchElementException - 扫描仪未按预期运行

java - 如何在 Java 中以更好的方式编写这些循环?

c++ - 比较 vector 和打印 bool

javascript - 当 ( for in ) 执行 javascript 时如何做某事?

javascript - 如何在评估缓冲区时根据缓冲区中的值暂停 RxJS 缓冲的可观察对象?

javascript:对象对象而不是集合中的值=(

Java - 使用 while 循环丢失第一个用户输入

javascript - 循环中异步函数的最后一个值