如何以成对方式添加两个数组 [英] How to add two arrays in pairwise fashion
问题描述
我想添加两个具有相同长度的JavaScript数组的值来获取第三个数组,以便第三个数组的第一个值是两个第一个数组的第一个值的总和,第二个值第三个数组是两个第一个数组的第二个值的总和,等等。例如:
I would like to add the values of two JavaScript arrays that have the same length to get a third array so that the the first value of the third array is the sum of the first values of the two first arrays, the second value of the third array is the sum of the second values of the two first arrays, etc. For example:
var array1 = [1,2,3];
var array2 = [4,1,0];
var array3 = array1 + array2;
我想要 array3
的结果是 [1 + 4,2 + 1,3 + 0]
= [5,3,3]
。
I would like the result of array3
to be [1+4, 2+1, 3+0]
= [5,3,3]
.
这与这个。我想添加数字而不是制作子数组。
This is not the same question as this. I would like to add the numbers and not make sub-arrays.
我知道你可以做 for(i = 0; i< array1.length; i ++){array3 [i] = array1 [i] + array2 [i]}
但我想知道是否有内置代码可以执行此操作。
I know that you can do for(i = 0; i < array1.length; i++){array3[i] = array1[i] + array2[i]}
but I would like to know if there is a built-in code that does this.
推荐答案
使用 数组#map()
方法
var array1 = [1, 2, 3];
var array2 = [4, 1, 0];
var array3 = array1.map(function(v, i) {
return v + array2[i];
})
console.log(array3);
对于最新的浏览器,请使用 ES 6箭头功能
For latest browser use it with ES6 arrow function
var array1 = [1, 2, 3];
var array2 = [4, 1, 0];
var array3 = array1.map((v, i) => v + array2[i])
console.log(array3);
对于较旧的浏览器,请检查地图方法的polyfill选项。
For older browser check polyfill option of map method.
这篇关于如何以成对方式添加两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!