Method: 1. Use the "for (var i=1;i
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript finds the sum of 1-n
If you want to find the sum of 1-n, you need to traverse the numbers 1~n, so for The initial condition of the loop can be set to i = 1, and the restriction condition can be i
for (var i = 1; i <= n; i++) { }
Then in the loop body "{}", add the i values of each loop. This requires an intermediate quantity sum to store the calculated value. The initial value of the variable sum must be 0, so as not to affect the result. There are two ways to write it (just choose one):
sum += i; //或 sum = sum + i;
After the loop ends, the value of variable sum will be the sum of 1-n, and then output it.
The complete implementation code is given below:
function sum(n) { //函数声明 var sum=0; //局部变量声明 for (var i=1;i<=n;i++){ //初始表达式,测试表达式,改变表达式 sum = sum + i; //将i+n的值给到sum } return sum; //返回sum值 } console.log(sum(2)); //控制台输出1-2数和 console.log(sum(3)); //控制台输出1-3数和 console.log(sum(4)); //控制台输出1-4数和 console.log(sum(5)); //控制台输出1-5数和 console.log(sum(6)); //控制台输出1-6数和 console.log(sum(7)); //控制台输出1-7数和 console.log(sum(8)); //控制台输出1-8数和 console.log(sum(9)); //控制台输出1-9数和 console.log(sum(10)); //控制台输出1-10数和
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to find the sum of 1-n in javascript. For more information, please follow other related articles on the PHP Chinese website!