Home  >  Article  >  Web Front-end  >  JavaScript defines a set of array sums

JavaScript defines a set of array sums

WBOY
WBOYOriginal
2023-05-15 21:27:37607browse

To define an array in JavaScript, you can use the following syntax:

var myArray = [1, 2, 3, 4, 5];

The above code defines an array named "myArray", which contains 5 numeric elements.

If you want to calculate the sum of all elements in the array, you can use the following code:

var myArray = [1, 2, 3, 4, 5];
var sum = 0;

for (var i = 0; i < myArray.length; i++) {
  sum += myArray[i];
}

console.log(sum);

In the above code, we define a variable named "sum" and initialize it is zero. Then use a for loop to iterate through each element in the array and add the value of each element to the variable "sum". The final result will be printed on the console.

This is a simple example, but in the actual development process, you may need to perform addition operations between multiple arrays, or need to use different accumulators to calculate different results. In this case, functions can be used to encapsulate the logic and return the results.

The following is a function definition to calculate the sum of any given array:

function sumArray(numbers) {
  var sum = 0;

  for (var i = 0; i < numbers.length; i++) {
    sum += numbers[i];
  }

  return sum;
}

var myArray = [1, 2, 3, 4, 5];
console.log(sumArray(myArray)); // 输出15

In the above code, we have defined a function called "sumArray" which accepts one parameter "numbers", represents the array to be added. The logic inside the function is similar to the previous example. It uses a for loop to iterate through each element in the array and add the value of each element to the variable "sum". Finally, the function returns the result (i.e. the sum of the addition operations).

Using the above function, one can easily calculate the sum of any array without the need to manually write a for loop every time like the previous example. For example:

var myArray1 = [2, 4, 6, 8, 10];
var myArray2 = [1, 3, 5, 7, 9];

console.log(sumArray(myArray1)); // 输出30
console.log(sumArray(myArray2)); // 输出25

In the above code, we define two different arrays and use the function "sumArray" to add them separately. The returned results are 30 and 25 respectively.

The above is the detailed content of JavaScript defines a set of array sums. 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