Home > Article > Web Front-end > How to add up in javascript
Javascript method to implement accumulation: first create the corresponding js sample file; then implement accumulation through "for(var i = 1;i <= 100;i){sum = i;}" and other methods. Can.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to accumulate in javascript?
JS common algorithm-accumulation/accumulation
Accumulation: Add a series of data to a variable. Finally, the cumulative result is obtained.
empty var sum = 0; for(var i = 1;i <= 100;i++){ sum += i; }
empty var h = 100; var sum = 0; for(var i = 0;i < 10;i++){ h = h / 2; sum += h; } sum = sum * 2 + 100;
Accumulation: Multiply a series of data into a variable to get the cumulative result.
empty var n = 100; var result = 1; for(var i = 1;i <= n;i++){ result *= i; }
General form:
Accumulation: v = e;
Accumulation: v *= e;
v represents accumulation Sum/accumulation, e represents the accumulation/accumulation term
Key points of the algorithm:
(1)Initialization
Initialization v:
Accumulation: v = 0;
Accumulation: v = 1;
e initialization, if the accumulation/product term is more complex, it may be decomposed into several sub-terms to be initialized separately. For example, in the problem of calculating pi, the accumulation term is decomposed into The three parts of the symbol, numerator and denominator
(2) The control condition of the loop
One is a fixed number of times, such as the problem of calculating the bounce distance, the problem of calculating the sum of the first 20 items of the sequence, the number of times It is not fixed, but must meet a certain condition: the problem of calculating pi requires that the absolute value of the last term be less than 10-6.
(3) Determine the accumulation/product term
For example, the sum of the first 20 items in a sequence is to use the sum of the current numerator and denominator as the next denominator, and the current denominator as the numerator;
Another example is to find the circumference of pi. The sign is inverted, the denominator is 2, and then the next term is obtained.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to add up in javascript. For more information, please follow other related articles on the PHP Chinese website!