Javascript method to find the sum from 1 to 100: 1. Create an HTML sample file and add a script tag; 2. Use "for(i=1;i<=100;i){sum=sum i }" statement can be used to find the sum from 1 to 100.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to find the sum from 1 to 100 in javascript?
very simple!
The js code is as follows:
<script> var sum=0; for(i=1;i<=100;i++){ sum=sum+i } document.write(sum); //计算结果是5050 </script>
Run this code to get the cumulative sum from 1 to 100, 1 2 3 4... 100=5050.
We also The sum requirement can be encapsulated into a function, the code is as follows:
<script> function add(start,end){ var sum=0; for(i=start;i<=end;i++){ sum=sum+i } return sum; } document.write(add(1,100)); </script>
The running result is still 5050.
Video tutorial recommendation: "javascript basic tutorial"
The above is the detailed content of How to find the sum from 1 to 100 in javascript. For more information, please follow other related articles on the PHP Chinese website!