Home > Article > Web Front-end > How to add numbers in js
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
To implement number addition in JavaScript
<code class="js">let num1 = 5; let num2 = 10; let sum = num1 + num2; console.log(sum); // 输出:15</code>
<code class="js">let num1 = 5; let num2 = 10; let sum = Number(num1) + Number(num2); console.log(sum); // 输出:15</code>
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>
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>
<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!