Home  >  Article  >  Web Front-end  >  How to add numbers in js

How to add numbers in js

下次还敢
下次还敢Original
2024-05-06 14:27:15583browse

The addition of numbers in JavaScript can be achieved by the following methods: using the plus operator ( ) using Number.prototype.valueOf() method using parseInt() and parseFloat() functions using Array.prototype.reduce() Method uses for loop

How to add numbers in js

To implement number addition in JavaScript

Method 1: Use the plus operator ( )

<code class="js">let num1 = 5;
let num2 = 10;
let sum = num1 + num2;

console.log(sum); // 输出:15</code>

Method 2: Use Number.prototype.valueOf() Method

<code class="js">let num1 = 5;
let num2 = 10;
let sum = Number(num1) + Number(num2);

console.log(sum); // 输出:15</code>

Method 3: Use JavaScript built-in functions parseInt() and parseFloat()

parseInt() and parseFloat() functions to convert strings to integers or floating point numbers. If the numbers are strings, you can use these functions to convert them to numbers and then add them.

<code class="js">let num1 = '5';
let num2 = '10';
let sum = parseInt(num1) + parseInt(num2);

console.log(sum); // 输出:15</code>

Method 4: Using the Array.prototype.reduce() method

The reduce() method can be used to perform an accumulation operation on the elements in an array.

<code class="js">let numbers = [5, 10];
let sum = numbers.reduce((total, current) => total + current, 0);

console.log(sum); // 输出:15</code>

Method 5: Use for loop

<code class="js">let num1 = 5;
let num2 = 10;
let sum = 0;

for (let i = num1; i <= num2; i++) {
  sum += i;
}

console.log(sum); // 输出:15</code>

The above is the detailed content of How to add numbers in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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