Javascript - 在单次迭代中对两个数组求和 [英] Javascript - Sum two arrays in single iteration

查看:41
本文介绍了Javascript - 在单次迭代中对两个数组求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个数字数组的每个值与其在不同数字数组中的对应值相加,并且我想在不遍历每个单独值的情况下执行此操作.
所以:

I want to sum each value of an array of numbers with its corresponding value in a different array of numbers, and I want to do this without looping through each individual value.
So:

var array1 = [1,2,3,4];
var array2 = [5,6,7,8];

var sum    = [6,8,10,12];

但是,我想一举完成,而不是这样做:

But, I'd love to do it in one fell swoop, instead of doing this:

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

谁能想到办法?我很难过.

Can anyone think of a way? I'm pretty stumped.

推荐答案

我知道这是一个老问题,但我刚刚和某人讨论了这个问题,我们想出了另一个解决方案.您仍然需要一个循环,但您可以使用 Array.prototype.map() 来完成此操作.

I know this is an old question but I was just discussing this with someone and we came up with another solution. You still need a loop but you can accomplish this with the Array.prototype.map().

var array1 = [1,2,3,4];
var array2 = [5,6,7,8];

var sum = array1.map(function (num, idx) {
  return num + array2[idx];
}); // [6,8,10,12]

这篇关于Javascript - 在单次迭代中对两个数组求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆