我有两个长度相同的数组,我想用reduce方法同时处理它们。类似于:
var arr1 = [2, 3, 4, 5, 6];
var arr2 = [5, 10, 4, 9, 5];
var productSum = arr1.reduce(function(sumOfProducts, item, secondArrayItem) {
/* here I would like to multiply item from arr1 by the item from arr2 at the same index */
return sumOfProducts + item * secondArrayItem;
}, 0, arr2)
console.log(productSum); // 131
当然,一种选择是使用currentIndex
从arr2
中访问正确的项目,但这种解决方案很丑陋,因为我正在访问函数范围之外的变量。
我的具体用例是,我有一个资源数组,例如var resources = [2, 5, 4, 6, 2]
,我想检查每个项目是否高于另一个数组中相应的资源成本,例如var cost = [3, 1, 0, 0, 1]
。
是否有一些不错的解决方案可以使用reduce()
函数?
arr2[i]
是否访问了有效的索引。 - Bergi