Home > Article > Web Front-end > How to sum in javascript (code example)
JavaScript is a commonly used programming language, often used for web development and dynamic effect implementation. Let’s introduce the code implementation of summation in JavaScript.
Method 1: Using the addition operator
In JavaScript, you can directly use the addition operator to sum values. For example, the code can be written like this:
var num1 = 10; var num2 = 20; var sum = num1 + num2; console.log(sum); // 输出30
The values of num1 and num2 can be modified as needed to obtain different sums.
Method 2: Use for loop
If you need to perform the sum operation of multiple numbers, you can also use for loop to achieve it. The code is as follows:
var nums = [10, 20, 30, 40, 50]; var sum = 0; for(var i = 0; i < nums.length; i++){ sum +=nums[i]; } console.log(sum); // 输出150
Store the values to be summed in the array nums, loop through the array, add each value, and finally find the sum.
Method 3: Use the reduce function
In addition to the for loop, JavaScript also provides a more concise method, which is to use the reduce function of the array to implement the summation operation. The code is as follows:
var nums = [10, 20, 30, 40, 50]; var sum = nums.reduce(function(preVal, curVal){ return preVal + curVal; }); console.log(sum); // 输出150
Using the reduce function of the array can directly accumulate and sum each value in the array without using a for loop.
Summary:
The above are the three methods of summation in JavaScript, which are implemented using the addition operator, for loop and reduce function respectively. Different scenarios can choose different methods according to needs to achieve more efficient and concise code.
The above is the detailed content of How to sum in javascript (code example). For more information, please follow other related articles on the PHP Chinese website!