简体   繁体   中英

What is the meaning of this JavaScript code [on hold]

 var total = 0; var total2 = 0; for (var number = 2; number < 15; number++) { total += number; for (var number2 = 1; number2 <= 12; number2++) { total2 = total + number2; } } 

I'm trying to figure out the value of total,total2, number, and number2. I don't expect an answer, I just want to know how to find the answers.

At the end of the script to display the result in the console.

console.log(total, total2);

While this is not about what's the final result. The meaning is total is the sum of every numbers between 2 and 14 and total2 is the sum every between 1 and 12 for each loop (like a multiply).

Of course, it has a purpose yes. Who knows why someone write this.

 var total = 0; var total2 = 0; for (var number = 2; number < 15; number++) { total += number; for (var number2 = 1; number2 <= 12; number2++) { total2 = total + number2; } } console.log('total:',total) console.log('total2:',total2) 

This is an example of a nested loop.

The outer for loop is run thirteen times for the values of number from 2 to 14 .

The inner loop is run twelve times per iteration of the outer loop.

The final value of total will be the sum of the numbers 2 to 14 ( 104 ).

total2 will be overwritten twelve times per iteration of the outer loop.

The final value of total2 will be 104 (the final value of total1 ) plus 12 (the final value of number2 ) = 116 .

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