Home >Web Front-end >Front-end Q&A >How to calculate addition n in JavaScript
In JavaScript, we can use loops or recursion to add n numbers. The specific implementation method is as follows:
1. Use a loop to add n numbers
1.1 for loop
Use a for loop to add each number . The sample code is as follows:
function sumByFor(n, arr) { var sum = 0; for (var i = 0; i < n; i++) { sum += arr[i]; } return sum; } var arr = [1, 2, 3, 4, 5]; console.log(sumByFor(arr.length, arr)); // 输出15
1.2 while loop
Use the while loop to add each number. The sample code is as follows:
function sumByWhile(n, arr) { var sum = 0, i = 0; while (i < n) { sum += arr[i]; i++; } return sum; } var arr = [1, 2, 3, 4, 5]; console.log(sumByWhile(arr.length, arr)); // 输出15
2. Use recursion to find the sum of n numbers
Use recursion to add the sum of the first number and the remaining numbers. The sample code is as follows:
function sumByRecursion(n, arr) { if (n == 1) { return arr[0]; } else { return arr[0] + sumByRecursion(n-1, arr.slice(1)); } } var arr = [1, 2, 3, 4, 5]; console.log(sumByRecursion(arr.length, arr)); // 输出15
The above are the implementations of three methods for calculating the sum of n numbers in JavaScript. The method using loops is simpler and more intuitive, while the method using recursion is more beautiful. In actual development, appropriate methods should be selected based on needs and scenarios.
The above is the detailed content of How to calculate addition n in JavaScript. For more information, please follow other related articles on the PHP Chinese website!