forEach() 和 reduce() 不使用参数

forEach() and reduce() not working with arguments

我有两个数组 (a,b),我的任务是找到它们体积的差异,即我必须将数组 a 的所有元素相乘,然后对数组 b 做同样的事情,然后将两者相减以找到区别。

我尝试将 forEach()reduce()arguments 结合使用,但似乎每个数组的最后一个元素都被遗漏了,我得到的输出是 NaN.

这是我的代码

  function findDifference(a, b) {
  var args = Array.prototype.slice.call(arguments);
  var results = [];
  args.forEach(function(argument){
    return argument.reduce(function(a,b){
     results.push(a*b);
    });
  });
  return results;
}

这是我对 findDifference([3, 2, 5], [1, 4, 4]);

的输出
[6, NaN, 4, NaN]

看起来乘法在每个数组的第二个元素处停止。有什么想法吗?

您可以将每个数组的所有乘法结果存储在 result 数组中,而不是将每个乘法都存储在结果数组中。

function findDifference(a, b) {
  var args = Array.prototype.slice.call(arguments);
  var results = [];
  args.forEach(function(argument){
    results.push(argument.reduce(function(a,b){
      return a*b;
    }));
  });
  
  return results;
}
console.log(findDifference([3, 2, 5], [1, 4, 4]));

为什么不直接乘以给定的数组并取结果的增量?

function findDifference(a, b) {
    return [a, b]
        .map(a => a.reduce((a, b) => a * b))
        .reduce((a, b) => a - b);
}

console.log(findDifference([3, 2, 5], [1, 4, 4]));

有参数。

function findDifference(a, b) {
    return Array.prototype
        .map.call(arguments, a => a.reduce((a, b) => a * b))
        .reduce((a, b) => a - b);
}

console.log(findDifference([3, 2, 5], [1, 4, 4]));