How to sum two arrays in ES6

青灯夜游
Release: 2022-05-19 18:14:08
Original
2413 people have browsed it

Summing method: 1. Use concat() to merge two arrays. The syntax "array1.concat(array2)" will add the elements of array 2 to the end of array 1; 2. Use reduce () Calculate the sum of merged arrays, the syntax is "array.reduce(function(p,c){sum=p c;})".

How to sum two arrays in ES6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

How to sum two arrays in ES6

1. Use concat() to merge two arrays into one array

The concat() method can connect two or more arrays and will add the elements of one or more arrays as parameters to the end of the specified array

var a = [1,2,3];
var b = [4,5,6];
console.log(a);
console.log(b);
var d = a.concat(b);
console.log(d);
Copy after login

How to sum two arrays in ES6

2. Use reduce() to calculate the sum of all elements in the merged array

reduce can traverse the array, let the two items before and after the array perform some calculation, and then return Its value, and continue the calculation without changing the original array, return the final result of the calculation; if no initial value is given, the traversal starts from the second item of the array.

The reduce() method receives a function as an accumulator, and each value in the array (from left to right) starts to be reduced and finally calculated to a value.

Summing example:

var a = [1,2,3];
var b = [4,5,6];
console.log(a);
console.log(b);
var d = a.concat(b);
var sum = 0;
d.reduce(function(pre,curr) {
sum=pre+curr;
return sum;
});
console.log(sum);
Copy after login

How to sum two arrays in ES6

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to sum two arrays in ES6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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