只是做一个小作业。我需要迭代到 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/