Home >Web Front-end >JS Tutorial >How to find the sum of values from n to m in javascript
In JavaScript, you can use the for loop and the "=" operator to find the sum of values from n to m, and implement the code "function sum(n,m){var sum=0;for(var i=n ;i
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript finds the sum of values from n to m
Implementation idea:
Find n to The sum of m values is to find the value of n...m, that is, the cumulative result of the range from n to m
You can use the for loop to control the cumulative range, fromi= n
, i<br>
In the for loop body, use =
for cumulative calculation
Implementation code:
function sum(n,m){ var sum=0; for(var i=n;i<=m;i++){ sum+=i; } console.log(sum); }
When n is 1 and m is 2, 3, 4, 5, the cumulative sum of values from n to m:
sum(1,2); sum(1,3); sum(1,4); sum(1,5);
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to find the sum of values from n to m in javascript. For more information, please follow other related articles on the PHP Chinese website!