简体   繁体   中英

How do I create an infinite addition output loop in JS/node?

I am new to JS. For fun I want to create an infinite loop that outputs the following way: 1+1=2, 2+2=4, 4+4=8, 8+8=16 and so on...This is what I have so far. I created a For loop to concise my theories/methods for practice, but I still can't get it to work properly.

 for (let i = 0; i < 5; i++) { num1 = i; sum = i * 2; answer = sum * 2; console.log(sum + " + " + sum + " = " + answer * i); }

At the moment you're just multiplying variables by two when really you want to take the result of adding two numbers together and use it in the next iteration.

Declare a step variable outside of the loop. On each iteration assign the the sum of two steps to an answer variable, log the result, and then assign answer to step .

 let step = 1; for (let i = 1; i < 10; i++) { let answer = step + step; console.log(`${step} + ${step} = ${answer}`); step = answer; }

Additional documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM