结合相同的大小,并返回总和的两个阵列 [英] Combining two arrays of same size and returns sum

查看:146
本文介绍了结合相同的大小,并返回总和的两个阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Javascript(或功能性的语法其他编程语言),如果我有同样大小的两个数组,说
A = [1,2,3,4] B = [5,6,7,8] ,什么是有以下结果的最有效的方法:
C = [6,8,10,12]

In Javascript (or any other programming language with a functional-like syntax), if I have two arrays of the same size, say a = [1,2,3,4] and b=[5,6,7,8], what is the most efficient way to have the following result: c=[6,8,10,12].

现在,我做的:

a.map(函数(X,I){
  返回X + B [I]
})

但我非常希望不涉及使用索引的解决方案。

but ideally I would like a solution that doesn't involve the use of indexes.

推荐答案

ES5阵列方法是伟大的,但老循环更快。

ES5 array methods are great, but old for loops are faster.

var sum = Array(a.length);
for(var i=0; i<a.length; ++i)
  sum[i] = a[i] + b[i];

这篇关于结合相同的大小,并返回总和的两个阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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