Home > Article > Web Front-end > How to add from 1 to n using javascript
In JavaScript, you can use the for loop statement and the " " operator to implement the operation from 1 to n, the syntax is "var sum=0;for (var i=1; i
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript implements adding from 1 to n
In javascript, if you want to add from 1 to n, you can use the for loop statement, just You need to add the traversed numbers in the loop body
for (var i = 1; i <= n; i++) { sum = sum + i; }
After the loop ends, the value of the variable sum is accumulated and the calculated result is output. It should be noted that the declaration and initialization of variable sum must be placed before the for loop, and the initialization value must be 0, so as not to affect the result of the addition operation.
The complete implementation code is given below:
function sum(n) { var sum=0; for (var i=1;i<=n;i++){ sum += i; } console.log(sum); }
When n is a different value, the output results are also different:
sum(2); sum(3); sum(4); sum(5); sum(6);
【 Related recommendations: javascript learning tutorial】
The above is the detailed content of How to add from 1 to n using javascript. For more information, please follow other related articles on the PHP Chinese website!