JavaScript——无法理解 Array.Map 和 Array.reduce

标签 javascript arrays function

我一直在研究 FCC(自由代码营)的一个问题,该问题需要扫描 2D 数组并从每个 1D 数组中找到最大元素,并将结果放入 1D 数组中。我在 GitHub 上发现了这个解决方案,但无法理解。

    function largestOfFour(arr) {
      return arr.map(function(group){
        return group.reduce(function(prev, current) {
          return (current > prev) ? current : prev;
        }, 0);
      });
    }
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

输出为 [5, 27, 39, 1001]

我的 console.log(arr) 给了我:4,5,1,3,13,27,18,26,32,35,37,39,1000,1001,857,1

  1. 作为函数参数传递时,二维数组如何转换为一维数组?

我的console.log(group)给了我:4,5,1,3(第一次),13,27,18,26(第二次),32,35,37,39(第三次)和1000 , 1001, 857, 1(第四次)。

  • 匿名函数如何能够将参数组作为 2D 内的单个 1D 数组。
  • 有人可以帮忙吗?

    最佳答案

    例如,当您使用 Array.map 时,它将处理数组中的每个元素。

    [1, 2, 3, 4].map(function (item) { return item; } ); 
    

    只会返回一个带有 [1, 2, 3, 4] 的数组,但是假设我们将每个值加倍,我们可以这样做。

    [1, 2, 3, 4].map(function (item) { return 2 * item; });
    

    返回 [2, 4, 6, 8]。

    因此,在您的示例中,您有一个二维数组。 Array.map 在第一层工作。所以在每次迭代中该组是

    • 第 1 -> [4, 5, 1, 3]
    • 第二 -> [13, 27, 18, 26]
    • 第三 -> [32, 35, 37, 39]
    • 第四 -> [1000, 1001, 857, 1]

    因此第 1 到第 4 个将被传递到 Array.reduce 函数中。 Reduce 只是根据传入的数组返回单个值,或者更好地放置

    The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

    这里的reduce中发生的事情是存储最大值,它从0开始,并在第一次迭代时与值4进行比较。由于4大于0,所以它被存储并成为我们的新最大值。然后它会针对 5 进行测试,并且由于 5 大于 4,因此会将其存储为新的最大值,依此类推。

    完成遍历后,它会生成该数组的最大值,并给出一个数字作为结果。因此,现在包含数组的映射的第一次迭代更改为数字,在这种情况下,Array.map 生成的数组的第一项应该是 5。

    我怀疑最终的输出是

    [5, 27, 39, 1001]
    

    关于JavaScript——无法理解 Array.Map 和 Array.reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40479929/

    相关文章:

    javascript - firebase 对象大小 : how to ignore properties with $?

    javascript - 在javascript中将数组转换为二维数组(方阵)

    c++ - 使用函数优化代码-数组中的最大元素

    function - R 中 `substitute` 的令人困惑的行为

    javascript - 如何在以编程方式创建的 iframe 的 onLoad 上调用 this.somefunction() ?

    javascript - 有没有办法动态创建嵌套的 div onclick?

    javascript - jQuery button click attr ('src' ) 返回 'Cannot read property ' on' of null'

    arrays - numpy 二维数组分区的优化方法

    c - 如何分配要存储到数组中的用户输入

    PHP - 强制函数评估?