How to sum in javascript (code example)

PHPz
Release: 2023-04-24 13:56:21
Original
4867 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!